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 value
property:
if(!/^[a-z0-9-]+$/i.test(someName.value)) {
//-------------------------^^^^^^^^^^
alert('Name can only be alpha numeric with hypen.');
return;
}
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 -
.
/^[a-z0-9]+[a-z0-9-]+[a-z0-9]+$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With