Tải bản đầy đủ - 0 (trang)
Chapter 9. Validation with PHP and JavaScript

Chapter 9. Validation with PHP and JavaScript

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

9.1ValidationandErrorReportingPrinciples

Thereisnothingworseforauserthanannoying,overly

persistent,inaccurate,oruninformativevalidation.Forexample,

errormessagesthatdescribeanerrorbutdon'tspecifywhich

fieldcontainstheerroraredifficulttocorrect.However,thereis

norecipeforbalancingvalidationwithsystemrequirements:

whatispleasingormandatedbyrequirementsinone

applicationmightbeannoyingoruselessinanother.Inthis

section,weconsiderpracticalvalidationmodelsforweb

databaseapplications.

Validationisactuallytwoprocesses:findingerrorsand

presentingerrormessages.Findingerrorscanbeinteractive,

wheredataischeckedasit'sentered,orpost-validation,where

thedataischeckedafterentry.Presentingerrorscanbefieldby-fieldwhereanewerrormessageispresentedtotheuserfor

eacherrorfoundoritcanbebatched,whereallerrorsare

presentedasasinglemessage.Thereareotherdimensionsto

validationanderrorprocessing,suchasthedegreeoferrorthat

istoleratedandtheexperienceleveloftheuser.However,

consideringonlythebasicprocesses,thechoiceofwhento

error-checkandwhentonotifytheuser,leadstofourcommon

approaches:



Interactivevalidationwithfield-by-fielderrors

Thedataineachfieldisvalidatedwhentheuserexitsor

changesthefield.Ifthereisanerror,theuserisalertedto

thaterrorandmayberequiredtofixtheerrorbefore

proceeding.



Interactivevalidationwithbatchederrors

Thedatainallfieldsisvalidatedwhentheuserleavesone

field.Ifthereareoneormoreerrors,theuserisalertedto

these,andcan'tproceedbeyondthecurrentpagewithout

fixingallerrors.



Post-validationwithfield-by-fielderrors

Theuserfirstentersalldatawithnovalidation.Thedatais

thencheckedanderrorsarereportedforeachfield,oneby

one.Theuserfixeseacherrorinturnandresubmitsthe

dataforrevalidation.



Post-validationwithbatchederrors

Theuserfirstentersalldatawithnovalidation.Thedatais

thenchecked,andallerrorsinthedataarereportedinone

messagetotheuser.Theuserthenfixesallerrorsand

resubmitsthedataforrevalidation.

InChapter8withoutdiscussingthedetailswecoveredseveral

simplepost-validationtechniquestocheckwhethermandatory

formdatawasenteredbeforeinsertingorupdatingdatainthe

database.Inaddition,weusedabatchreportingmethod,

whereerrorswerereportedasalistbyconstructinganerror

pageusingatemplate.

Intheexamplesinthischapter,wediscussadditionalvalidation

techniquestoinspectbothmandatoryandoptionalfields.We

usethesetechniquestocreateabatcherrorreportinChapter

10.Examplesofcompletevalidationcodeforacustomerdetails

formarelistedinChapter17.



9.1.1ModelsThatDon'tWork

Interactivemodelsaredifficulttoimplementintheweb

environment.Server-sidescriptsareimpracticalforthistask,

becauseanHTTPrequestandresponseisrequiredtovalidate

eachfieldthat'sentered.Thisisusuallyunacceptable,because

theuserisrequiredtosubmitthedataafterenteringeachfield.

Theresultisthatresponsetimesarelikelytobeslowandthe

serverloadhigh.

Client-sidescriptscanimplementaninteractivemodel.

However,validationontheclientsideshouldnotbetheonly

methodofvalidationbecausetheusercanpassivelyoractively

bypasstheclient-sideprocesses.Wediscussthepartially

interactivesolutionofincludingclient-sidescriptswithanHTML

formlaterinthischapter.



9.1.2ModelsThatDoWork

Post-validationmodelsarepracticalinwebdatabase

applications.Bothclient-andserver-sidescriptscanvalidateall

formdataduringthesubmissionprocess.

Inmanyapplications,reasonablycomprehensivevalidationis

performedontheclientsidewhentheuserclickstheform

submitbutton.Client-sidevalidationreducesserverand

networkload,becausetheuser'sbrowserensuresthedatais

validpriortotheHTTPrequest.Client-sidevalidationisalso

usuallyfasterfortheuser.

Ifclient-sidevalidationsucceeds,dataissubmittedtothe

serverandthesame(oroftenmorecomprehensive)validation

isperformed.Duplicatingclientvalidationontheserveris

essentialbecauseoftheunreliabilityofclient-sidescriptsand

lackofcontrolovertheclientenvironment.



Thepost-validationmodelcanbecombinedwitheitherfield-byfieldorbatcherrorreporting.Forserver-sidevalidation,the

batchmodelispreferabletoafield-by-fieldimplementation,as

thelatterapproachhasmoreoverheadandisusuallyslower

becauseeachformerrorrequiresanadditionalHTTPrequest

andresponse.

Forclient-sidepost-validation,eithererror-reportingmodelcan

beused.Theadvantageofthefield-by-fieldmodelisthatit

leadstheuserthroughtheprocessofcorrectingthedataand

thecursorcanbedirectedtothefieldcontainingtheerror,

makingerrorcorrectioneasier.Thedisadvantageisthatseveral

errorsrequireseveralerrormessages,andthiscanbe

frustratingfortheuser.Theadvantageofthebatchapproachis

thatallerrorsarepresentedinonemessagebutthe

disadvantageisthatthecursorcan'teasilybedirectedtothe

fieldrequiringcorrectionanditssometimesuncleartotheuser

howtocorrectthedata.



Server-sidevalidationisessentialtosecureawebdatabaseandto

ensurethatsystemandDBMSconstraintsaremet.

Client-sidevalidationmaybeimplementedinadditiontoserver-side

validation,butallclient-sidefunctionalityshouldbeduplicatedatthe

serverside.Nevertrusttheuserortheclientbrowser.

Thechoiceofwhichreportingmodeltousedependsonthesizeand

complexityoftheformandonthesystemrequirements.



9.2Server-SideValidationwithPHP

Inthissection,weintroducevalidationontheserverusingPHP.

Weshowyouhowtovalidatenumbersincludingcurrenciesand

creditcards,stringsincludingemailaddressesandZipCodes,

anddatesandtimes.Wealsoshowyouhowtocheckfor

mandatoryfields,fieldlengths,anddatatypes.ManyofthePHP

functionsweuseincludingtheregularexpressionandstring

functionsarediscussedindetailinChapter3.

Weillustratemanyofourexamplesinthissectionwithacase

studyofvalidatingcustomerdetails.Thetechniquesdescribed

herearetypicalofthosethatvalidateaformaftertheuserhas

submitteddatatotheserver.Weshowhowtoextendand

integratethisapproachfurtherinChapter10sothatthebatch

errorsarereportedaspartofacustomerform,andweshowa

completedcustomerentryformandvalidationinChapter17.



9.2.1MandatoryData

Testingwhethermandatoryfieldshavebeenenteredis

straightforward,andwehaveimplementedthisinourexamples

inChapter8.Forexample,totestiftheuser'ssurnamehas

beenentered,thefollowingapproachisused:

///ValidatetheSurname

if(empty($surname))



formerror($template,"Thesurnamefieldcannotbeblank.",$e



Theformerror()functionoutputstheerrormessageasabatch



errorusingatemplateandisdiscussedindetailinChapter8.

Forsimplicityandcompactnessintheremainderofour

examplesinthischapter,weomittheformerror()functionfrom

codefragmentsandsimplyoutputtheerrormessagesusing

print.



9.2.2ValidatingStrings

Inthissection,wediscussnonnumericvalidation.Webegin

withthebasicsofvalidatingstrings,andthendiscussthe

specificsofemailaddresses,URLs,andZiporpostcodes.



9.2.2.1Basictechniques

It'slikelythatmostofthedataenteredbyuserswillbestrings

andrequirevalidation.Indeed,checkingthatstringscontain

legalcharacters,areofthecorrectlength,orhavethecorrect

formatisthemostcommonvalidationtask.Stringsarepopular

fortworeasons:first,alldatafromaformthatisstoredinthe

superglobals$_GETand$_POSTisofthetypestring;and,

second,somenonstringdatasuchasadateofbirthoraphone

numberislikelytobestoredasastringinadatabasetable

becauseitmaycontainbrackets,dashes,andslashes.However,

despitedatesandphonenumbersbeingsometimesstoredas

strings,wediscusstheirvalidationinSection9.2.2.5.

Thesimplesttestofastringistocheckifitmeetsaminimum

ormaximumlengthrequirement.Forexample:

if(strlen($password)<4||strlen($password)>8)

print"Passwordmustcontainbetween4and8characters";



Lengthvalidationcanalsobeperformedusingaregular

expression,asweshowinlaterexamplesinthissection.Our

mysqlclean()andshellclean()functionsalsoincludeanimplicit

maximumlengthvalidation.AsdiscussedinChapter6,these

functionsshouldbeusedasafirststepinvalidationthathelps

tosecureanapplication.

Commontestsforlegalcharactersincludecheckingifstrings

areuppercase,lowercase,alphabetic,oraredrawnfroma

definedcharacterset(suchas,forexample,alphabeticstrings

thatmayincludehyphensorapostrophes).InPHP,the

is_string()functioncanbeusedtocheckifavariableisastring

type.However,thisisoflimiteduseinvalidationbecausea

stringcancontainanycharacterincluding(orevenexclusively)

digitsorspecialcharacters.It'smoreusefultotestwhat

charactersareinthestringordetectcharactersthatshouldn't

bethere.

Regularexpressionsofferthreeshortcutsforuseinbasictests

thatarediscussedinChapter3.Totestifastringisalphabetic,

use:

if(!ereg("^[[:alpha:]]$",$string))

print"Stringmustcontainonlyalphabeticcharacters.";



Totestifastringisuppercaseorlowercase,use:

if(ereg("^[[:upper:]]$",$string))

print"Stringcontainsonlyuppercasecharacters.",;



if(ereg("^[[:lower:]]$",$string))



print"Stringcontainsonlylowercasecharacters";



TheexpressionsworkfortheEnglishcharactersets,andalso

workforFrenchifyousetyourlocaleatthebeginningofthe

scriptusing,forexample,setlocale(`LC_ALL','fr').Inthe

future,itshouldworkforalllocalitiesand,therefore,these

techniquesareusefulforinternationalizingyourapplication.

Ifyou'reworkingwithonlytheEnglishlanguageasimpler

alphabetictestworks:

if(!eregi("^[a-z]*$",$string))

print"Stringmustcontainonlyalphabeticcharacters.";



Forothercharactersets(orifyouwantdetailedcontrolover

Englishvalidation),ahandcraftedexpressionworkswell.For

example,thefollowingworksasanalphabetictestforSpanish:

if(!eregi("^[a-zñ]*$",$string))



print"Lacadenadebecontenersolamentecaracteresalfabetic



Sometimesit'seasiertocheckwhatcharactersshouldn'tbe

there.Forexample,atouruniversity,studentemailaccounts

mustbeginwithanS:

if(!ereg("^S",$text))

print"StudentaccountsmustbeginwithS.";



However,forthissimpleexample,aregularexpressionwillrun

slowerthanusingastringlibraryfunction.Instead,abetter

approachistousesubstr():

if(substr($text,0,1)!="S")

print"StudentaccountsmustbeginwithS.";



Ingeneral,youshouldusestringfunctionsforlowcomplexity

tasks.

Forourcustomercasestudy,wemightallowthefirstnameand

surnameofthecustomertocontainonlyalphabeticcharacters,

hyphens,andapostrophes;whitespace,numbers,andother

specialcharactersaren'tallowed.Forthefirstnameweuse:

elseif(!eregi("^[a-z'-]*$",$firstName))

print"Thefirstnamecancontainonlyalphabetic".

"charactersor-or'";



Lengthvalidationandcharacterchecksareoftencombined.For

example,thecustomer'smiddleinitialmightbelimitedto

exactlyonealphabeticcharacter:

if(!empty($initial)&&!eregi("^[a-z]$",$initial))



print"Theinitialfieldmustbeemptyoronecharacterinle



Theifstatementcontainstwoclauses:acheckastowhether

thefieldcontainsdataand,ifthat'strue,acheckofthe

contentsofthefieldusingeregi().AsdiscussedinChapter2,

thesecondclauseischeckedonlyifthefirstclauseistrue

whenanAND(&&)expressionisevaluated.Ifthevariableis

empty,theeregi()expressionisn'tevaluated.

Theexpression^[a-z]$isthesameas^[a-z]{1}$.Tocheckif

astringisexactlyfouralphabeticcharactersinlengthuse^[az]{4}$.Tocheckifit'sbetweentwoandfourcharactersuse

^[a-z]{2,4}$.



9.2.2.2ValidatingZipandpostcodes

Ziporpostcodesarenumericinmostcountriesbutaretypically

storedasstringsbecausespaces,letters,andspecialcharacters

aresometimesallowed.Inourcustomercasestudy,wemight

validateZipCodesusingasimpleregularexpression:

//ValidateZipcode

if(!ereg("^([0-9]{4,5})$",$zipcode))

print"Thezipcodemustbe4or5digitsinlength.";



ThispermitsaZipCodeofeitherfourorfivedigitsinlength;

thisworksforbothU.S.ZipCodes,andAustralia'sandseveral

othercountries'postcodes,butit'sunsuitableformanyother

countries.Forexample,postcodesfromtheUnitedKingdom

includelettersandaspaceandhaveacomplexstructure.

Forcompletevalidation,wecouldadaptourZiporpostcode

validationtomatchthecountrythattheuserhasentered.

Example9-1showsavalidationfunctionthatadaptsformany



Zipandpostcodes.Thefinalfivecasestatementscheck

postcodesthatmustincludespaces,dashes,andletters.



Example9-1.Acodefragmenttovalidatemany

popularZipandpostcodes

functioncheckcountry($country,$zipcode)

{

switch($country)

{

case"Austria":

case"Australia":

case"Belgium":

case"Denmark":

case"Norway":

case"Portugal":

case"Switzerland":

if(!ereg("^[0-9]{4}$",$zipcode))

{



print"Thepostcode/zipcodemustbe4digitsinlength

returnfalse;



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

Chapter 9. Validation with PHP and JavaScript

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

×