Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript only allow alphanumeric and hyphen - value in text field

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.

like image 664
Nomad Avatar asked Sep 05 '25 01:09

Nomad


1 Answers

Access the input's value property:

if(!/^[a-z0-9-]+$/i.test(someName.value)) {
   //-------------------------^^^^^^^^^^
   alert('Name can only be alpha numeric with hypen.');
   return;
}

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 -.

/^[a-z0-9]+[a-z0-9-]+[a-z0-9]+$/
like image 195
Michael Berkowski Avatar answered Sep 07 '25 04:09

Michael Berkowski