Help with Validation

Discussion in 'JavaScript' started by Arcos, Dec 30, 2006.

  1. #1
    Can someone help me out and tell me how to chance this code to validate alpha-numeric?

    Really appreciate your help!!

    function isValidCode(field)
    {
    var valid = "0123456789+";
    for (var i=0; i < field.length; i++)
    {
    temp = field.substring(i, i+1);
    if (valid.indexOf(temp) == "-1")
    {
    alert("Invalid post code.Please try again.");
    return false;
    }
    }
    return true;
    }
     
    Arcos, Dec 30, 2006 IP
  2. nocookies

    nocookies Peon

    Messages:
    57
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    It might work. BTW, indexOf() returns -1, and not "-1".
    There is much shorter version using regular expressions:

    
    function isValidCode(field)
    {
       return field.search(/^[0-9+]*$/)!=-1;
    }
    
    Code (markup):
     
    nocookies, Dec 30, 2006 IP
  3. Arcos

    Arcos Peon

    Messages:
    474
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks for your reply.

    I am not exactly great with Java and this has me stumped!

    THe code checks a field and if the field entry is anything but numbers it returns an error.

    OX28 4BS returns an error

    11630 is fine

    I need it to allow text and numbers

    OX28 4BS No Error

    11630 No Error
     
    Arcos, Dec 31, 2006 IP
  4. nocookies

    nocookies Peon

    Messages:
    57
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    It's only a matter of changing the regex:

    
    function isValidCode(field)
    {
       return field.search(/^[0-9a-zA-Z]*$/)!=-1;
    }
    
    Code (markup):
    Just put inside the square brackets ([]) the range of characters you'd like to accept.
     
    nocookies, Dec 31, 2006 IP