Skip to content
Advertisement

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement