Tải bản đầy đủ - 0 (trang)
Hack 27. Validate a Postal Code

Hack 27. Validate a Postal Code

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

Theuserenterszerotofivedigitsinthetextfield(thishack

testsonlythefirstfivedigitsofaZIPCode),thenpressesTab

orclicksoutsideofthefield.Theapplication'scodethen

automaticallyvalidateswhattheusertyped.

Thecodemakessurethattheuserenteredfivedigits,andonly

fivedigits,intothefield.ThewebpageimportsaJavaScriptfile

namedhacks3_7.js,whichcontainsthefollowingcode:



window.onload=function(){

varzip=document.getElementById("zip5");

varcit=document.getElementById("city");

zip.onblur=function(){

if(this.value&&cit.value){chkZipcode(zip.value);}

//validateactualzipcode:

//httpRequest("GET","http://www.parkerriver.com/s/zip?

//encodeURIComponent(cit)+"&stat

//encodeURIComponent(_st),

//true,handleResponse);

};

};



functionchkZipcode(zipVal){

varre=/^\\d{5}$/;

if(!re.test(zipVal)){

document.getElementById("message").

innerHTML="Pleaseenteravalidzipcod

}

}

functionhandleResponse(){

varxmlReturnVal;

try{

if(request.readyState==4){

if(request.status==200){

xmlReturnVal=request.responseXML;

if(xmlReturnVal!=null){



//validateenteredzipcodeagainstthisva

}

}else{

//request.statusis503

//iftheapplicationisn'tavailable;

//500iftheapplicationhasabug

alert(

"Aproblemoccurredwithcommunicating

"theXMLHttpRequestobjectandtheser

");

}

}//endouterif

}catch(err){

alert("Itdoesnotappearthattheserver"+

"isavailableforthisapplication.Please"+

"tryagainverysoon.\\nError:"+err.message);

}

}



Thewindow.onloadeventhandler,triggeredwhenthebrowser

finishesloadingthewebpage,setsupthebehaviorforthe

application.Withinthewindow.onloadeventhandlerisanonblur

eventhandlerfortheZIPCodetextfield.Thiseventhandleris

triggeredwhentheuserpressesTaborclicksoutsideoftheZIP

Codefield.Thecodeverifiesthattheuserhastypedvaluesinto

thecityandZIPCodetextfields(if(cit.value&&zip.value)),and,

ifso,validatestheformatoftheZIPCodevalueusing

chkZipcode().

Thisfunctionusesaregularexpressionthatrepresentsaphrase

madeupoffivenumbers.ThecodeteststheenteredZIPCode

valueagainstthisregularexpressiontodetermineiftheZIP

Code'sformatiscorrect.



Aregularexpressionrepresentsatemplatefortestingstringsof

characters.Theregularexpressionusedherelooksforalineoftext

madeupofjustfivenumbers(the^means"beginningoftheline,"and

$isaspecialsymbolfor"endoftheline").\\disapredefinedcharacter

classforadigit[09].



Iftheformatisnotcorrect,thecodegeneratesausermessage.

Thewebpagecodeincludesadivelementwithanidofmessage

tocontainthesenotifications:



varre=/^\\d{5}$/;

if(!re.test(zipVal)){

document.getElementById("message").

innerHTML="Pleaseenteravalidzipcode.
}



HackingtheHack

Ifyouwanttoensurethatthefivenumbersrepresentareal

ZIPCode,youcanusethecodein"FetchaPostalCode"[Hack

#34]torequestapostalcodeforacertaincityandstate.That

hackrequeststheZIPfromawebservice;yourcodecanthen

comparethisvaluewiththevalueenteredbytheuser.



SomecitieshavemultipleZIPCodes,and"FetchaPostalCode"[Hack

#34]returnsonlythefirstZIPCodefoundforacity/statecombination.

Therefore,thismethodisnotafoolproofwayofvalidatingeveryZIP

Codevalue.Youcouldaltertheservercomponentthatconnectswith

thewebservicetoreturnallZIPCodesfoundforaspecifiedcity,but

thismethodwouldstillrequiremoreuserinteractiontonarrowdown

thechoicestooneZIPCode.



Chapter4.PowerHacksforWeb

Developers

Hacks2842

Webdevelopmentthesedaysincreasinglyinvolvesmaking

connectionswithcoolandusefulwebAPIs,suchasGoogle

Maps,Yahoo!Maps,andWeather.com.Thefirstfivehacksin

thischaptercoversomeusesoftheseAPIs;"UseAjaxwitha

Yahoo!MapsandGeoURLMash-up"[Hack#32]integratesdata

fromtheGeoURLservice.ThegrowthofAjaxtechniquesalso

makesitnecessarytotakesomeapplicationsoff-line(for

example,whenmovingfromtheterminaltoanairlinerwitha

laptop),andthusrequirespersistentstorageofdataonthe

clientside.Tothisend,thischapterincludesahackdescribing

thenewopensourceclientstoragetoolcalledAMASS.Italso

delvesintothetypicaltasksthatinhabitawebdeveloper's

calendar,suchasaddingemailcapabilitiestoAjaxapplications,

accessingandcreatingHTTPcookies,debuggingtheDOM

objectsinAjaxsoftware,andfindingoutthebrowser'slocale

information.Finally,thischapter'slasthackcreatesan"Ajaxy"

RSSfeedreader.(RSSReallySimpleSyndication,inoneofits

flavorsisanXMLfileformatthatplaysanimportantroleata

numberofnews-andissue-orientedwebsites.)



Hack28.GetAccesstotheGoogleMapsAPI



CreateapplicationsthatcombineGoogleMapsandyour

ownservercomponents.

Formaploversanddevelopers,perhapstheonlythingcooler

thanGoogleMapsistheGoogleMapsAPI.TheAPIallows

developerstoinventnewAjax-styleapplicationswithGoogle

Maps.ItismadeupofJavaScriptobjectsandmethodsthatlet

youcontroltheappearanceofmapsonwebpages,addcontrols

tothem,andcreatenewclickablebehaviors.

TousetheAPI,youhavetofirstobtainadeveloper'skeyfrom

Google.Thisisveryeasy.Simplygoto

http://www.google.com/apis/maps/,specifythewebsitethat

willuseGoogleMaps(suchashttp://www.parkerriver.com),

andclickonaformbutton,andGooglegeneratesakeyforyou.

Thisisalongbunchofalphanumericcharacters,suchas:



CDROAAAANJd_PEMs2vnU_f04htHhZhSa_9HZXsWbc66iRLah8f17kmN8QRSryZ5



GoogleObjects

Youspecifythekeyinyourwebpagewhenyourscripttag

importsGoogle'sJavaScriptlibraryforGoogleMaps.Hereis

whatthetoppartofanHTMLpagelookslikewhenenablingthe

GoogleMapsAPI,includingthekeyspecification:


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">