Reputation: 1408
I'm trying to check if there's a number in a text input
using regular expression. Here's the code:
var regex = /^[0-9]+$/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
It works well, but if I add text, then backspace all the way, I get "bad". How can I make it log "good" when there isn't anything in the text input
? I don't want to allow spaces, but I want to allow an empty input
.
I tried:
var regex = /\s ^[0-9]+$/;
But then whatever I insert in the input
, I always get "bad".
Upvotes: 1
Views: 7371
Reputation: 513
This might fit , either you test for your Exp (^[a-zA-Z0-9]+$)
or for an empty string (^$)
.
var regex = /(^$)|(^[a-zA-Z0-9]+$)/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
Upvotes: 5
Reputation: 68393
try this (* in place of +)
var regex = /^[0-9]*$/;
if (myInput.val().test(regex)) {
console.log("number");
} else {
console.log("bad");
}
Upvotes: 1