Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A simpler form of numeric validation

Validation

A simpler form of numeric validation

by  GUJUm0deL  Posted    (Edited  )
There are many ways to perform validations for numbers, this one works the best (well, for me at least). This has been tested on IE, NS and FF.

Code:
<script>
    function checknumber(data) {
    [color red]var checkOK = "()-0123456789. ";[/color]
    var checkStr = data.value;
    var allValid = true;
    var allNum = "";
    
      for (i = 0;  i < checkStr.length;  i++) {
        ch = checkStr.charAt(i);
      for (j = 0;  j < checkOK.length;  j++)
        if (ch == checkOK.charAt(j))
          break;
        if (j == checkOK.length) {
          allValid = false;
          break;
        }
        if (ch != ",")
          allNum += ch;
        }
        if (!allValid) {
          alert("Please enter a valid phone number");
          data.value = "";
        return (false);
      }
    }
</script>

This portion of the code [color red]var checkOK = "()-0123456789. ";[/color], allows you to specify what chars can be passed. In my case, this is a phone number validation, I am allowing all numeric chars, parenthesis, dash, space and a period. This way the user can enter (123) 333-4555 or 888.888.8888 or (210) 333 3333 or any other combination.

To call this function, you do: [color blue]onChange="checknumber(this);"[/color], you can use any even handler, doesn't have to be onChange. You can also call this function accross multiple fields the SAME way: [color blue]onChange="checknumber(this);"[/color]
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top