INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Validation

A simpler form of numeric validation by GUJUm0deL
Posted: 3 Jan 06 (Edited 10 Feb 06)

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) {
    var checkOK = "()-0123456789. ";
    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 var checkOK = "()-0123456789. ";, 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: onChange="checknumber(this);", you can use any even handler, doesn't have to be onChange.  You can also call this function accross multiple fields the SAME way: onChange="checknumber(this);"

Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close