Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    js form field validations functions

    use in form fields - onBlur="chkalpha(this)"

    function chknum(field) {
    var valid = "0123456789";
    var ok = "yes";
    var temp;
    for (var i=0; i<field.value.length && ok == "yes"; i++) {
    temp = "" + field.value.substring(i, i+1);
    if (valid.indexOf(temp) == "-1") { var ok = "no"; }
    }
    if (ok == "no") {
    alert("Invalid entry! Only numeric data is accepted!");
    field.value=""; field.focus();
    field.select();
    }
    }

    function chkalpha(field) {
    var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    var ok = "yes";
    var temp;
    for (var i=0; i<field.value.length && ok == "yes"; i++) {
    temp = "" + field.value.substring(i, i+1);
    if (valid.indexOf(temp) == "-1") { var ok = "no"; }
    }
    if (ok == "no") {
    alert("Invalid entry! Only alphabetic data is accepted!");
    field.value=""; field.focus();
    field.select();
    }
    }

    function chkalphanum(field) {
    var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@_-. ";
    var ok = "yes";
    var temp;
    for (var i=0; i<field.value.length && ok == "yes"; i++) {
    temp = "" + field.value.substring(i, i+1);
    if (valid.indexOf(temp) == "-1") { var ok = "no"; }
    }
    if (ok == "no") {
    alert("Invalid entry! Only alphanumeric data is accepted!");
    field.value=""; field.focus();
    field.select();
    }
    }

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    And your question is?

    Your code is extremely clumsy and old-fashioned. You should use regular expressions instead.
    Alphabetic only will reject Mary-Lou O'Flanaghan in a name field. Numeric only will reject 999-999-999 in a phone number field or 12345-7890 in a zip field.

    BTW, when posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.


    It is your responsibility to die() if necessary….. - PHP Manual
    Last edited by Philip M; 01-13-2012 at 03:26 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •