HEEN
HEEN

Reputation: 4721

Regex for allowing character, numbers and - in javascript

I have a textbox where I want user to only input values like below example

I-MH-NGPR-UBR-0001

It means, a user can add only numbers, alphabets and -. Other than this it should not allow user to enter anything.

How to do this in javascript

Upvotes: 0

Views: 81

Answers (2)

schaturv
schaturv

Reputation: 122

Try this on your HTML itself no need of javascript also.

<input type="text" name="myTextBox" pattern="^[a-zA-Z0-9-]+$" title="Please enter only alphabets numbers or -">

Upvotes: 0

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You can try this:

^[a-zA-Z0-9-]+$

Demo

const regex = /^[a-zA-Z0-9-]+$/m;
const str = `I-MH-NGPR-UBR-0001`;
if (str.match(regex))
  console.log("matched");
else
   console.log("not matched");

Upvotes: 2

Related Questions