Tải bản đầy đủ - 0 (trang)
Chapter 13. Regular Expressions and Pattern Matching

Chapter 13. Regular Expressions and Pattern Matching

Tải bản đầy đủ - 0trang

13.4FormValidationwithRegularExpressions

WhenyoufilloutaformontheWeb,youaretypicallyaskedfor

yourname,phone,address(apop-upmenuofallthestatesis

usuallyprovided),andthenallsortsofcreditcardstuff.

Sometimesittakesfourorfivetriestogetitrightbecauseyou

didn'tcompletetheformexactlythewayyouwereasked.A

messagewillappearandyouwon'tbeallowedtosubmitthe

formuntilyougetitright.BehindthescenesaJavaScript

programisvalidatingtheform.



13.4.1CheckingforEmptyFields

There'saformwaitingtobefilledout.Someofthefieldsare

optional,andsomearemandatory.Thequestionis,didtheuser

fillinthemandatoryfields?Ifhedidn't,theformcan'tbe

processedproperly.Checkingforemptyornullfieldsisoneof

thefirstthingsyoumaywanttocheck.



Example13.36







CheckingforEmptyFields



1functionvalidate_text(form1){

2if(form1.user_name.value==""||form1.user_name.valu

null){

alert("Youmustenteryourname.");

returnfalse;

}

3if(form1.user_phone.value==""||form1.user_phone.va



null){

alert("Youmustenteryourphone.");

returnfalse;

}

else{

4returntrue;

}

}










CheckingforEmptyfields



5

Pleaseenteryourname:


6



Pleaseenteryourphonenumber:


7











EXPLANATION

1. Auser-definedfunctioncalledvalidate_text()is

defined.Ittakesoneparameter,areferencetoa

form.

Ifthevalueinthefirsttextfieldisanemptystring

(representsastringwithnotext)ornull(representsnovalue),

theuserissentanalertaskinghimtofillinhisname.Ifafalse

valueisreturned,theformisnotsubmitted.



Ifthevalueinthesecondtextfieldisanemptystringornull,

theuserissentanalertaskinghimtofillinhisphone.Ifafalse

valueisreturned,theformisnotsubmitted.

Ifbothtextboxeswerefilledout,atruevalueisreturned,

andtheformwillbesubmittedtotheserver'sCGIprogram

whoseURLislistedintheactionattributeoftheform.

TheonSubmiteventistriggeredwhentheuserpressesthe

submitbutton.Thehandlerfunction,validate_text(),willbe

calledwithareferencetothisform.

Theinputtypeforthisformisatextboxthatwillgetthe

nameoftheuser.

Anothertextboxiscreatedtoholdthephonenumberofthe

user.SeeFigure13.36.



Figure13.36.Theuserleftthephonefieldempty,

sotheformwasnotsubmitted.



13.4.2CheckingforNumericZipCodes



Ifyouasktheuserforafive-digitzipcode,itiseasytocheck

usingaregularexpressionbymatchingforexactlyfivedigits:



/^\d{5}$/

Anotherwaytosaythesamething:



/^[0-9][0-9][0-9][0-9][0-9]$/

Somelongerzipcodescontainadashfollowedbyfour

numbers.Thislongzipcodeformatcouldberepresentedas:



/^\d{5}-?\d{4}$/

Thebeginningandendoflineanchorspreventthematched

stringfromcontaininganyextraneouscharactersateitherend

ofthestring.SeeExample13.37.



Example13.37





TestingforaValidZipCode



1functionok_Zip(zip){

2varregex=/^\d{5}$/;//Matchfor5numbers

3if(regex.test(zip.value)==false){

alert("Zipcodemustcontainexactlyfivenumbers!");

zip.focus();

returnfalse;

}

4if(zip.value==""){



alert("Youmustenterazipcode");

zip.focus();

returnfalse;

}

returntrue;

}







Enteryourzipcode:


name="zipcode"

size=5>


value="Checkzip"

5onClick="if(ok_Zip(ZipTest.zipcode)){alert('Zipis

valid.')}">










EXPLANATION

1. Thefunction,calledok_Zip(),isdefinedtovalidate

thezipcodeenteredbytheuser.

Theregularexpressionreads:Lookforexactlyfivedigits.

Thebeginningoflineandendoflineanchorsensurethatthere

willnotbeanyextraneouscharactersbeforeorafterthefive

digits.

Theregularexpressiontest()methodchecksthatthevalue

enteredbytheuserisavalidzipcode.Ifnot,analertdialog

boxwilltelltheuser,focuswillreturnedtothetextbox,and

falsewillbereturned.



Iftheuserdoesn'tenteranything,analertdialogboxwill

appear,focuswillbereturnedtothetextbox,andfalsewillbe

returned.

TheonClickeventistriggeredwhentheuserclicksthe

"Checkzip"button.AJavaScriptstatementtocalltheok_Zip()

functionisassignedtotheevent.Iftheuserenteredavalidzip

code,thealertdialogboxwillpopupandsayso.SeeFigure

13.37.



Figure13.37.Theuserentersafive-digitzipcode

(top);theuserentersnothing(middle);theuser

enters4digitsand1letter(bottom).



13.4.3CheckingforAlphabeticData

Totestforentriesthatmustconsiststrictlyofalphabeticinput,

suchasaname,state,orcountryfield,theregularexpression

charactersetcanbeused;forexample,/[a-zA-z]+/isaregular

expressionthatmatchesastringcontainingoneormore

uppercaseorlowercaseletters,and/^[a-zA-Z]+$/matchesa

stringcontainingonlyoneormoreuppercaseorlowercase



letters,becausethecharactersetisenclosedwithinthe

beginningandendinganchormetacharacters.Torepresentone

ormorealphanumericwordcharacters,[A-Za-z0-9_],youcan

usethe\wmetasymbol;forexample,/\w+/representsoneor

morealphanumericwordcharacters.



Example13.38





TestingforAlphabeticCharacters



1functionokAlpha(form){

2varregex=/^[a-zA-Z]+$/;//Matchforupper-orlowercase

if(regex.test(form.fname.value)==false){

alert("Firstnamemustcontainalphabeticcharacters!

form.fname.focus();

returnfalse;

}

3if(form.fname.value==""){

alert("Youmustenteryourfirstname.");

form.fname.focus();

returnfalse;

}

4returntrue;

}







5
method="post"

action="/cgi-bin/testing.pl"

6onSubmit="returnokAlpha(this)">

Enteryourfirstname:


7name="fname"

size=20>





8









EXPLANATION

1. AfunctioncalledokAlpha()isdefined.Ittakesone

parameter,areferencetoaform.Itspurposeisto

makesuretheuserenteredonlyalphabetic

charactersintheform.

Aregularexpressioniscreated.Itreads:Startingatthe

beginningoftheline,findoneormoreuppercaseorlowercase

lettersinthecharacterclass[A-Za-z]followedbytheendof

lineanchor($).Theregularexpressionistestedagainstthe

inputthatcameinfromatextboxnamedtext.Ifitdoesn't

match,thealertboxwillnotifytheuser,andfalseisreturnedto

theonSubmithandleronline6.Theformwillnotbesubmitted.

Iftheuserdidn'tenteranythingatallandthefieldisempty,

anotheralertwillbesenttotheuser,andfalsewillbereturned.

Theformwillnotbesubmitted.

Iftheuserenteredonlyalphabeticcharactersinhisname,

truewillbereturned,andtheformwillbesubmitted.

ThisiswheretheHTMLformstarts.

TheonSubmithandlerwillbetriggeredwhentheuser

pressesthesubmitbutton,andtheokAlpha()functionwillbe

called,passingareferencetotheformcalledalphaTest.

Theuserentershisnameinthetextfieldcalledfname.



Afterfillingouttheform,theuserwillpressthesubmit

button,therebytriggeringtheonSubmithandleronline6.See

Figure13.38.



Figure13.38.Theuserhasadigitinhisname.He

canonlyenteralphabeticcharacters,orhewill

seethewarning.



13.4.4RemovingExtraneousCharacters

RemovingSpacesandDashes

Toremoveanyunwantedspacesordashesfromuserinput,the

Stringobject'sreplace()methodcanbeusedtofindthe

charactersandreplacethemwithnothing,asshowninExample

13.39.



Example13.39





RemovingSpacesandDashes









RemovingSpacesandHyphens





1varstring="444-33-1234"

2varregex=/[-]+/g;

3varnewString=string.replace(regex,"");

document.write("Theoriginalstring:"+string);

document.write("
Thenewstring:"+newString+"
"







EXPLANATION

1. Thestringcontainsnumbers,spaces,anddashes.

Thevariablecalledregexisassignedaregularexpression,

whichmeans:Searchforoneormorespacesordashes,

globally(multipleoccurrenceswithinthestring).

Thereplace()methodsearchesinthestringforspacesand

dashes,andifitfindsany,replacesthemwiththeemptystring,

"",returningtheresultingstringtonewString.Tochangethe

originalstring,thereturnvalueofthereplace()methodcanbe

returnedbacktotheoriginalstring:var

string=string.replace(regex,"");



Figure13.39.Thereplace()methodisusedto

removeanyspacesordashes.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 13. Regular Expressions and Pattern Matching

Tải bản đầy đủ ngay(0 tr)

×