Can I validate a string with only alphanumeric, space and underscore chars only

etabalon
Mega Expert

Good day!

Can I validate a string and only accepts upper/lower case alphanumeric, space, dash and underscore chars only?

I'm trying to validate a server name so users cannot use like $ or % characters as part of the server name.

Thanks,

Enrique

1 ACCEPTED SOLUTION

drjohnchun
Tera Guru

Here's a regex that should work, including numeric characters:



if (/^[-\w ]+$/.test(server_name)) {   }   // server_name is OK


else { }   // server_name NOT OK



\w includes [a-zA-Z0-9_]



I suggest running this in both client and server.



Please feel free to connect, follow, mark helpful / answer, like, endorse.


John Chun, PhD PMP see John's LinkedIn profile


visit snowaid


View solution in original post

11 REPLIES 11

drjohnchun
Tera Guru

Here's a regex that should work, including numeric characters:



if (/^[-\w ]+$/.test(server_name)) {   }   // server_name is OK


else { }   // server_name NOT OK



\w includes [a-zA-Z0-9_]



I suggest running this in both client and server.



Please feel free to connect, follow, mark helpful / answer, like, endorse.


John Chun, PhD PMP see John's LinkedIn profile


visit snowaid


etabalon
Mega Expert

Thanks Abhinay and John. I'll try your solution and will get back to you guys. I appreciate your help.


Enrique


Abhinay Erra
Giga Sage

John's approach is much cleaner than mine.


etabalon
Mega Expert

John & Abhinay,



Is this part "(/^[-\w ]+$/.test(server_name)" somewhat a javascript syntax? I don't see an example like this on SN's wiki.



Thanks!


Hi Enrique - as Abhinay said, the script is using a Regular Expression to test for the condition you specified:



/^[-\w ]+$/.test(server_name)



  1. / is the start of the regular expression
  2. ^ is the start of the test string server_name
  3. [-\w ] means to look for any of the characters "-", "\w" (alphanumeric and underscore = [a-zA-Z0-9_]), or " " (space). The square bracket means "any character listed in the square brackets".
  4. + means one or more characters matching only what's listed in the square brackets
  5. $ means to test to the end of the string server_name
  6. / is the end of the regular expression


If it comes across any character not listed, like a special character, it'll return false.



The .test() method is explained at RegExp.prototype.test() - JavaScript | MDN



I've also created an interactive test case at Online regex tester and debugger so you can try out test cases for yourself (I've added "gm" flags so you can see several matching/non-matching test cases at once below; you won't need those flags in your actual test script).



In the screenshot below, the strings in blue background are OK (match), those in white background are NOT OK (non-match):


find_real_file.png



Please feel free to connect, follow, mark helpful / answer, like, endorse.


John Chun, PhD PMP see John's LinkedIn profile


visit snowaid