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

Abhinay Erra
Giga Sage

You can write an onChange client script on the server name field



if(newValue.match(/[a-zA-z-_\s]/g).length!=newValue.length){


alert('Please enter only upper/lower case alphanumeric, space, dash and underscore chars');


}



//Edit: Modified script a little bit


Abhinay, thank you for sharing the solution. I modified it to exclude space and add dash, and it works for me 95%



What is not working, is if user adds only special characters in the field, script does not alert and does not go further either. I suspect this is because in such a case string is null and .length can't calculate on that. Any ideas, how to get around it?



if(newValue.match(/[a-z0-9-]/ig).length!=newValue.length) {


g_form.setValue('email_address', "");


...}


Hi Vladmir - as you suspected, it's the match() that returns null in case of no match and subsequently results in an error. You can test for the null condition, but I'd just use



if (!/^[a-z0-9-]+$/i.test(newValue)) {


  g_form.setValue('email_address', "");


  ...


}


Vladi
Tera Contributor

Thanks a lot, John. Expression written this way did the trick.