help with javascript validation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • runway27
    Banned
    New Member
    • Sep 2007
    • 54

    help with javascript validation

    i have a registration page where a user fills up a form such as username, first name, phone number etc.

    i need to do a validation for the following fields. any help will be greatly appreciated.

    1. for a text field if for example a user hits the space bar and then types the information with the validation i have the code ignores those initial spaces but actually these are spaces i need to insert these values in a database so these spaces may cause an error.

    how to validate these initial spaces and tell the user not to use spaces at the beginning of a textfield

    my code at present is =

    var username = document.regist rationform.user name
    var re = /^\s{1,}$/g;

    if ((username.valu e==null) || (username.value =="") || (username.lengt h=="") || (username.value .search(re))> -1)
    {
    alert("Please Enter a User Name")
    username.value= ""
    username.focus( )
    return false
    }

    2. validation of special characters such as = !"£$%_^&*(). In general all the various special characters

    my code at present is =

    var postcode=docume nt.registration form.postcode
    var postcodestrippe d = postcode.value. replace(/[\(\)\.\-\ ]/g, '');

    if (isNaN(parseInt (postcodestripp ed)))
    {
    alert( "The post code contains illegal characters" );
    postcode.value= ""
    postcode.focus( );
    return false
    }

    3. validation of numbers = the code i have validates for numbers only if the first characters are letters but if there are letters in between the validation does not work. ex= ab12 validates however 12ab does not validate

    var pcontactnumbert f=document.regi strationform.pc ontactnumbertf

    var pcontactnumbert fnumber = document.regist rationform.pcon tactnumbertf.va lue;
    var checkfornumber = parseFloat(pcon tactnumbertfnum ber);

    if ( isNaN( checkfornumber ) )
    {
    alert( "Please enter a numeric number" );
    document.regist rationform.pcon tactnumbertf.fo cus();
    document.regist rationform.pcon tactnumbertf.se lect();
    return false
    }


    4. validating for characters only and nothing else. ex= name and not name123


    5. validating for numerics only and nothing else. ex= 123 and not 123name


    for all the above 5 questions i would really appreciate if someone can provide the appropriate code that needs to be written in order to validate each individual point i have mentioned.

    thanks a lot.
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    Wrap your code in a function, say validateForm(), and call it on onsubmit event of the form.

    Comment

    Working...