JS Regex to exclude some numbers

2019-05-18 19:46发布

问题:

I have a field where I need to collect single number

<input type="text" patern="" name="number" required="required" />

Now value can be anything 1-9999 however I have some numbers I don't allow, say

15
21 
532 

Is there a regex pattern I can use to force form submission to fail if one of this numbers have been entered?

回答1:

Try this regex:

/^(?!(?:15|21|532|0+)$)\d{1,4}$/

If you look carefully you will see that I included the number 0 in the disallowed list of 15, 21, 532. The reason for this is that the regex matches any number having 1 to 4 digits, but you only want the range 1-9999.

Click the links below for a running demo of this regex.

Regex 101

JS Fiddle



回答2:

Try setting type="submit" to disabled if 15, 21 , 532 value of input type="number" , using String.prototype.match()

var input = document.querySelector("input[type=number]")
var label = document.querySelector("[for=number]");
input.oninput = function() {
  var val = this.value;
  var matches = ["15","21","532"];
  var match = matches.indexOf(val) !== -1;
  this.nextElementSibling.disabled = match;
  this.style.color = match ? "red" : "inherit";
  label.innerHTML =  match ? "Invalid number: <mark style=color:red>" 
                             + val + "</mark>" 
                           : "";
}
<form>
  <input type="number" min="1" max="9999" pattern="" name="number" required="required" id="number" />
  <input type="submit" /><br />
  <label for="number"></label>
</form>



回答3:

function isValidNumber(num){
  if (isNaN(+num))
    return false;

  var cant_match = [ 15, 21, 532 ];
  return !( cant_match.indexOf(+num) >= 0 );
}


// Example call
isValidNumber( document.querySelector("input[name=number]").value );

Pretty simple:

  • isNaN(+num) fails if the value passed to the function is something other than a real or whole number (e.g., '32 456' fails)
  • the value passed is then checked against the array of bad numbers; if there is an index >= 0, then the number was found in the array