Pin Me

Validating Input at the Client: check numeric value fields

written by: Carmelo Carbonara•edited by: Linda Richter•updated: 10/1/2008

Input fields that are expected to collect only numeric values can be validated at the client's browser

  • slide 1 of 3

    Introduction

    The code view below uses a text input tag and we're expecting a non-negative integer for the quantity value. The div tag is a space where we can write a message if necessary.

    Checking for numeric values may require a series of tests and steps:

    • first trim the value
    • if it's not at all numeric stop and alert the user
    • if it is numeric, is it a non-negative number; otherwise alert the user
    • if we require integers, round the value
  • slide 2 of 3

    Code view for Checking Numeric Values

    This example applies the function chkField(whichObj) to the onblur event of the input field. The function chkField(whichObj) passes execution to testNumeric(whichObj) and expects a return value of true or false - if false, stop and ask the user for valid input. This could be applied as an onsubmit event if the quantity input field were part of a form. If the value entered for quantity is anything other than a positive integer it stops and alerts the user to enter a valid quantity.

    Code view

    Quantity&nbsp;<input name="qty" type="text" id="qty" style="display:block;margin-top:5px;margin-bottom:5px;" onblur='chkField(this)' />

    <input name="submit" type="submit" id="submit" style="display:block;" value="submit"/>

    <div id="messageDiv" style="margin:5px;"></div>

    <script language="JavaScript" type="text/javascript">

    function myObj(tagID) {return document.getElementById(tagID) ; };

    function testNumeric(whichObj)

    {

    // first trim the field

    whichObj.value=whichObj.value.replace(/(^\s*)|(\s*$)/g, "" );

    // check if the input is at all numeric

    if(isNaN(whichObj.value)==true){ return false}

    // check if the numeric is non-negative

    if((whichObj.value) <= 0 ){ return false}

    // if only integers are expected, round the value

    whichObj.value=Math.round(whichObj.value)

    // all OK return true

    return true

    }

    function chkField(whichObj)

    {

    if (testNumeric(whichObj)==false){whichObj.focus();whichObj.style.background="lightyellow";myObj("messageDiv").innerHTML="Please enter a valid quantity!";}

    }

    </script>

  • slide 3 of 3

    Conclusion

    Checking for numeric values involves a few steps. We could require validation within a range or as an appropriate date string. We may also want to check for blank fields and trim leading and trailing spaces and linefeeds.