Nomad
Nomad

Reputation: 1102

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.

Upvotes: 4

Views: 11357

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270627

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]+$/

Upvotes: 5

Berne
Berne

Reputation: 627

Notice that "-" is a special character. I don't know whether the regex engine of the browsers consider it been a special character. But I would recomend you to escape it as "[a-z0-9\-]". Also, the negation should be put inside the class, as "[^a-z0-9\-]". And finally, it shouldn't contain a start and end mark (^ and $). So, I think it would be like /[^a-z0-9\-]/.test(...)

Upvotes: -1

Related Questions