سؤال

When using type="number" on an input field, regex validation does not appear to work.

<input type="number" step="any" min="0" max="24" value="0">

The new broswer based validation using step, min, max works as expected. However this is not consistent accross browsers?

http://jsfiddle.net/EkL3k/1/


QUESTION

How to make a number field validate using regular expression?

I'm also interested in other factors that differentiate a number and text field if anyone has information.

NOTES

I have discovered that checking for an empty string causes validation to fire IF the conditions on the number field are not met.

هل كانت مفيدة؟

المحلول

A number field performs its own validation, if it contains a non-numerical character, the value will automatically be removed until a correct value is given. You can see this with a console.log(value).

So you could also check for an empty string

function check(value, msg) {
  var valid = ((value != '') && /^\d*\.?\d*$/.test(value));    
  if (valid) {
      document.getElementById(msg).style.display = "none";
  } else {
      document.getElementById(msg).style.display= "inline";
  }
  return valid;
}

http://jsfiddle.net/EkL3k/6/

نصائح أخرى

RegEx does not work because the returned value is a number, not a string. It works 'as expected' when you force the returned value to string format:

var valid = /^\d*\.?\d*$/.test(String(value));

You might want to read How to get the raw value an <input type="number"> field? as it suggests you don't have to validate a type=number input.

add this code and add an id to your input.

$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) || 
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});
});

http://codepen.io/anon/pen/IDEGu

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top