Javascript regex only alphabet, number and underscore
javascript, regex
Solution
- The `\w` is a handy regex escape sequence that covers letters, numbers and the underscore character
- You should test the entire string for valid characters by anchoring the validity test at the start (`^`) and end (`$`) of the expression
- The regular expression `test` method is faster than the string `search` method
- You can also test for one or more characters using the `+` quantifier
To summarise (in code)
var re = /^\w+$/;
if (!re.test(field.value)) {
alert('Invalid Text');
return false;
}
return true;
Alternatively, you can test for any invalid characters using
/\W/.test(field.value)
`\W` being any character other than letters, numbers or the underscore character.
Then you might also need to add a length check to invalidate empty strings, eg
if (/\W/.test(field.value) || field.value.length === 0)
Problem
I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass. ``` function validText(field) { var re = /[a-zA-Z0-9\-\_]$/ if (field.value.search(re) == -1) { alert ("Invalid Text"); return false; } } ``` A valid input would be something like '`Valid_Input123`' invalid ``` 'Invalid-Input !' ```