0

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

2
  • Try \w- or [a-zA-Z0-9-] in your regex. Commented Apr 4, 2017 at 5:40
  • @Abhishekgurjar - Can't use \w, because it matches on underscores. Commented Apr 4, 2017 at 5:48

2 Answers 2

2

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");

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.