I have a text field, whose value I am reading. I want to only allow alphanumeric characters and hyphen – value.
The regex I have so far doesn’t seem to fire if I enter values like abc$d or w2w,2 or we&*23 etc.
var someName = document.getElementById("sometextField");
if(/^[a-z0-9-]+$/i.test(someName.value))
{
alert('Name can only be alpha numeric with hypen.');
return;
}
Please help. Thanks for your help and time.
Access the input’s
valueproperty:Update
To allow a hyphen only in the middle of the expression, not at the beginning or end, you can use the following. There are likely to be better ways, but this should do the job. You have three groups of
[a-z0-9]+, but the middle one also permits-. The start and end groups don’t permit-.