Validating postal code and phone number according to state

Discussion in 'JavaScript' started by bali2003, Apr 3, 2008.

  1. #1
    I have a form with a drop down menu with states:

    state a
    state b
    state c
    etc (50 states)

    I need to validate the postal code field AND the phone number field so that:

    if state is 'a' postal code should start with 01 AND phone should start with 900
    if state is 'b' postal code should start with 02 AND phone should start with 901
    if state is 'c' postal code should start with 03 AND phone should start with 923
    etc with 50 states

    you get the idea

    if it doesn't match an error message should show
    "your postal code should start with xx"
    and/or
    "your phone number should start with xxx"

    For states dropdown i'm using id=states
    For post code textfield I'm using ID=post_code
    For Phone tex_field I'm using ID=telephone_number

    ...............................................

    The following code validates one variable (postal code) but I would need to validate both

    Thanks in advance


    .............................


    <html>
    <head>
    <script>
    var provPostal = [];
    provPostal['a']='01';
    provPostal['b']='02';
    provPostal['c']='03';
    provPostal['d']='04';
    provPostal['e']='28';

    function validate(){
    var province = document.getElementById( 'province' ).value;
    var postal = document.getElementById( 'postal' ).value;

    if ( postal.length != 5 ) {
    alert( 'Postal must be five characters long!' );
    return false;
    } else if ( postal.charAt( 0 ) != provPostal[ province ].charAt( 0 )
    || postal.charAt( 1 ) != provPostal[ province ].charAt( 1 ) ) {
    alert( 'Province ' + province + ' needs to start with ' + provPostal[ province ] );
    return false;
    }

    return true;
    }
    </script>
    </head>
    <body>
    <form onSubmit='return validate();'>
    Province: <select id='province'>
    <option value='a'>a</option>
    <option value='b'>b</option>
    <option value='c'>c</option>
    <option value='d'>d</option>
    <option value='e'>e</option>
    </select>
    Postal: <input type='text' id='postal' />
    <input type='submit'>
    </form>
    </body>
    </html>
     
    bali2003, Apr 3, 2008 IP