Alexglvr
Alexglvr

Reputation: 437

How to check the validity of a number type input sing javascript?

I have implemented in a form a number type input, with specified min and max :

<input class="qty_input" name="quantit" type="number" value="5" min="1" max="50" maxlength="2" style="width:4em;"></input>

The input type number works : if something else then a number is entered or if the number value is not in the specified range, the input becomes Red.

I have a javascript function that submit the form on input change.

<script type="text/javascript">
(function($) {

  function doAjax() {
    $.ajax({
        url : "blabla",
        type: "POST",
        data : $("#form-configurator").serializeArray(),
        dataType: 'json',
        success: function(data)
        {
            console.log(data);
        },
        error: function ()
        {

        }
    });
  }
$('input[type=number]').change(function() {

    // test Validity

    doAjax();
  });
})(jQuery);
</script>

I would like to test before running the doAjax() function if the number input is valid.

Is there a simple way to do that, like testing a "valid" parameter of the number type input? (it should exists as the input performs some tests itself…)

Thank you for your help,

Alex

Upvotes: 1

Views: 2534

Answers (3)

Kyle
Kyle

Reputation: 887

This can be accomplished without duplicating the validation rules via checkValidity():

$('input[type=number]').change(function() {
    if ($('input[type=number]')[0].checkValidity()) {
        doAjax();
    }
});

Upvotes: 0

Nicolas Albert
Nicolas Albert

Reputation: 2596

Here a live sample: http://jsfiddle.net/zueku6mo/

$('input[type=number]').change(function() {
    var min = $(this).attr("min") * 1;
    var max = $(this).attr("max") * 1;
    var val = $(this).val().length ? $(this).val() * 1 : NaN;
    // test Validity
    if (val >= min && val <= max) {
       $(this).css("background-color", "white");
       doAjax();
    } else {
       $(this).css("background-color", "red"); 
    }
});
  • cast min & max attribute to number with * 1
  • retrieve the current value and cast it to number if not empty
  • do some math that failed if there is a NaN value
  • set the background red to signal the value error

Upvotes: 0

PSR
PSR

Reputation: 40338

You can use isNaN() function to validate the input is a number or not. and you can add another if condition like

if(isNaN(value) || value <1 || value > 50)
 return ;
else 
    your logic     

It will return true if that value is not a number.If it is number,then it will return false.

see here

Upvotes: 3

Related Questions