Javascript Validation

download Javascript Validation

of 7

Transcript of Javascript Validation

  • 8/12/2019 Javascript Validation

    1/7

    Any sort of interactive site is going to have form inputs a place where your users input whothey are, what they want to buy, where they live, and so forth. This data is passed to whateverhandles your back end a Perl CG script, a P!P engine, a database like "racle, or some othertechnology you#ve invested in. $hatever system is back there, you can bet that it doesn#t

    appreciate having its time wasted with bogus information, and chances are the user doesn#tappreciate it either. f the data the user submits to the CG contains an error, there will be anoticeable lag typically several seconds before the information travels over the nternetto the server, is e%amined on the server, and then returns to the user along with an irritatingerror message.

    f you run a little preliminary validation of the user#s form input before the form is submitted,there will be no wait time. Client&side validation is instantaneous because it doesn#t have totransmit any data. 'ava(cript catches any erroneous data the user enters before it goesanywhere.

    )ouble&checking the data on the server remains necessary, in case the user has turned'ava(cript off or somehow finds a way to circumvent the client&side validation, eithermaliciously or by accident. *or the ma+ority of your users, 'ava(cript form validation will save alot of time up front.

    The Scripts Purpose

    This script accompanies an !T- form. $hen the user clicks the Submitbutton on the form,the form data is sent to a 'ava(cript validation function that checks each aspect of the input tomake sure that it is in the appropriate format. ach form element is evaluated according tospecified criteria. f the script finds an error in one of the fields, it sends back a warninge%plaining how the string doesn#t conform. The fairly robust string&handling and regular&e%pression techni/ues available in 'ava(cript handle this checking process.

    checkWholeForm()

    A master function, called checkWholeForm()is placed at the top of the page that contains a

    form.

    function checkWholeForm(theForm) {

    var why = "";

    why += checkEmail(theForm.email.value);

    why += checkhone(theForm.!hone.value);

    why += checkawor#(theForm.!awor#.value);

    why += check$ername(theForm.uername.value);

    why += iEm!ty(theForm.notem!ty.value);

    why += i%ifferent(theForm.#ifferent.value);

    for (i=&' n=theForm.ra#io.lenth; in; i++) {

    if (theForm.ra#io*i.checke#) {

  • 8/12/2019 Javascript Validation

    2/7

    var checkvalue = theForm.ra#io*i.value;

    break;

    ,

    ,

    why += check-a#io(checkvalue);

    why += check%ro!#own(theForm.chooe.electe#n#e/);

    if (why 0= "") {

    alert(why);

    return fale;

    , return true; ,

    This function calls a series of subfunctions, each of which checks a single form element forcompliance with a specific string format and returns a message describing the error. f thefunction returns an empty string, we know the element complies.

    checkUsername()

    !ere#s the routine that checks to see if the user entered anything at all in the uernamefield.

    0$e#ll use the same routine to check each form field for blankness.1

    function check$ername (trn) {

    var error = "";

    if (trn == "") { error = "1ou #i#n2t enter a uername.3n"; ,

    $e pass the value of the username field to this function, which compares that value to anempty string 0221. f the two are the same, we know that the username field is blank, so wereturn the warning string to our master function. f it#s not blank, we move along to the ne%thurdle. $e want to permit only usernames that are between 3 and 45 characters. $e checkthe length of the string, and re+ect it if it#s too short or too long.

    if ((trn.lenth 4) 55 (trn.lenth 6 7&)) {

    error = "8he uername i the wron lenth.3n"; ,

    6e%t, we want to forbid certain characters from appearing in usernames. (pecifically, we wantto allow only letters, numbers, and underscores. $e can test for that using regular e%pressionsand the tet()method. The regular e%pression functions found in 'ava(cript 4.7 are similar toPerl#s regular e%pressions, with a bit of simplification when it comes to synta%. f you know Perl,you should have no trouble wielding 'ava(cript#s regular e%pressions. The 'ava(cript regulare%pression 93W9is a standard character class that#s handily predefined to mean 2any character

  • 8/12/2019 Javascript Validation

    3/7

    other than letters, numbers, and underscores.2 (o we set the variable illeal:hare/ual tothat regular e%pression, and then test the uernamestring against that variable to see if amatch is found. f it is, we throw up a warning.

    var illeal:har = 93W9;

    99 allow only letter' number' an# un#ercore

    if (illeal:har.tet(trn)) {

    error = "8he uername contain illeal character.3n";

    ,

    8y now, we#ve run the username through three tests. f it#s passed all three, it#s "9 by us. $egive the username a passing grade and move along to the ne%t field.

    checkPassword()

    *or the password field, we want to constrain the length again 0this time, we#ll keep it between: and ; characters1, and we want to allow only letters and numbers no underscores thistime. (o we have to use a new regular e%pression to define which characters we#re banning.This one, like the last one, includes 3W everything but letters, numbers, and underscores

    but we also need to e%plicitly mention underscores, so as to permit only letters and numbers.!ence< 9*3W9.

    function checkawor# (trn) {

    var error = "";

    if (trn == "") {

    error = "1ou #i#n2t enter a !awor#.3n";

    , var illeal:har = 9*3W9; 99 allow only letter an# number

    if ((trn.lenth ?, @>A, and &>B, each followed by the +/uantifier, which means >one or more,? and we use

    the earch()method to make sure they#re all there

  • 8/12/2019 Javascript Validation

    4/7

    ele if (0((trn.earch(9*a>?+9) 6 >7)

    CC (trn.earch(9*@>A+9) 6 >7)

    CC (trn.earch(9*&>B+9) 6 >7))) {

    error = "8he !awor# mut contain at leat one

    u!!ercae letter' one lowercae letter'

    an# one numeral.3n";

    ,

    checkEmail()

    6e%t we want to see if the email address the user entered is real. The most effective way to dothis is to go out on the 6et and ask the domain the user claims to hail from if that the person

    actually has an account. 8ut this takes a big toll on the machine that#s running the checks and it isn#t possible with 'ava(cript anyway. $ith 'ava(cript we can check to see if the emailstring looks like an email address. $e want it to follow this format< some characters, then an atsymbol 0@1, then some more characters, then a dot 0.1, then two or three more characters, andthat#s it. This won#t be perfect validation it is possible to slip phony non&*C&compliantaddresses by it but it#s normally good enough. f the pattern doesn#t match, we re+ect theemail address.

    The regular e%pression that e%presses the format goes something like thisnumeric character

    if (iJaJ(!arent(tri!!e#))) {

    error = "8he !hone number contain illeal character."; ,

    Then we count the length of the number. t should have e%actly ten digits any more or less,and we re+ect it.

    if (0(tri!!e#.lenth == 7&)) {

    error = "8he !hone number i the wron lenth.

    Kake ure you inclu#e# an area co#e.3n"; ,

    isDifferent()$e want to do a few more kinds of validation. f you present a license or something similar in ate%t bo% for the user to accept, you want to make sure that it hasn#t been altered when theform is submitted. That#s done very simply by comparing the submitted string with the stringyou were e%pecting.

    function i%ifferent(trn) {

    var error = "";

    if (trn 0= ":an32t touch thi0") {

    error = "1ou altere# the inviolate te/t area.3n"; ,

    Alternately, you can use the on:hane()method to catch the user in the act of modifying thete%t and stop them before they submit the form.

    checkRadio()

    To make sure that a radio button has been chosen from a selection, we run through the arrayof radio buttons and count the number that have been checked. ather than sending the wholeradio ob+ect to a subfunction, which can be problematic 0because the radio ob+ect has no

  • 8/12/2019 Javascript Validation

    6/7

    property indicating which value has been chosen1, we pre&process the radio form element in afor loop and send that result to a subfunction for evaluation.

    for (i=&' n=theForm.ra#io.lenth; in; i++) {

    if (theForm.ra#io*i.checke#) {

    var checkvalue = theForm.ra#io*i.value;

    break; , ,

    why += check-a#io(checkvalue);

    function check-a#io(checkvalue) {

    var error = "";

    if (0(checkvalue)) {

    error = "leae check a ra#io button.3n";

    ,

    return error; ,

    check Dropdown()

    *inally, we want to make sure that the user has selected an option from our drop&down menu0and not the first option, which isn#t an option at all, but +ust a 2Choose one2 header1. *or this,we use the select ob+ect#s electe#n#e/property, which returns the inde% of the selectedoption. f the inde% is 5, we re+ect the input.

    function check%ro!#own(choice) {

    var error = "";

    if (choice == &) {

    error = "1ou #i#n2t chooe an o!tion

    from the #ro!>#own lit.3n"; , return error;

    ,

    odin! hallen!es

    Lalidation basically consists of comparing one thing to another, which is easy, especially with'ava(cript. The part that re/uires a bit of ingenuity is creating the regular e%pressions. Themore comple% the e%pression, the harder it is to write. After some practice and immersion inthe world of regular e%pressions, though, they can become second nature.

  • 8/12/2019 Javascript Validation

    7/7

    Lalidation also comes in more comple% flavors than we#ve covered here. *or e%ample, you maywish to validate a credit card number. An algorithm called the -uhn modulus&45 formulachecksthe validity of a given credit card number. n a case like this, there#s no need to re&invent thewheel. Mou can grab a simple script from brain+ar.com or a more complete version from'ava(cript (ource.

    Usin! The Script

    All of the functions are included in a file called validate.+s,which can be called with the S-:attribute of a S:-8tag at the top of the form page. "r, if you wish, you can paste thecontents of this file into the top of your !T- page. f you prefer, you can validate each formelement as soon as the user moves on to the ne%t element using the onLlur()event handler

    instead of onSubmit(). As always, remember to validate important form data on the back endas well, because most efforts at client&side validation can be spoofed.

    http://whatis.techtarget.com/definition/0,289893,sid9_gci214514,00.htmlhttp://www.brainjar.com/js/validation/http://www.brainjar.com/js/validation/http://javascript.internet.com/forms/val-credit-card.htmlhttp://developer.apple.com/internet/webcontent/examples/validate_source.htmlhttp://developer.apple.com/internet/webcontent/examples/validate_source.htmlhttp://whatis.techtarget.com/definition/0,289893,sid9_gci214514,00.htmlhttp://www.brainjar.com/js/validation/http://javascript.internet.com/forms/val-credit-card.htmlhttp://developer.apple.com/internet/webcontent/examples/validate_source.html