Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I have a textbox where I want user to only input values like below example
textbox
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.
numbers
alphabets
-
How to do this in javascript
\w-
[a-zA-Z0-9-]
\w
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");
Add a comment
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 -">
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
\w-or[a-zA-Z0-9-]in your regex.\w, because it matches on underscores.