Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validating forms with an exception

Status
Not open for further replies.

angela

Programmer
May 5, 2000
3
US
I have spent so much time on it that I've got myself confused!&nbsp;&nbsp;I am trying to make a form with and address. (city, state, and zip) where it will validate it.&nbsp;&nbsp;The city must be greater than 2 characters long, with no numbers, the state must be 2 characters long with no numbers.&nbsp;&nbsp;The zip, either 5 or 10 characters long.&nbsp;&nbsp;If any of these are wrong, I need an alert to come up.&nbsp;&nbsp;This I can do fine.&nbsp;&nbsp;<br><br>Here's the problem:&nbsp;&nbsp;If zip is correct, the city and state can be blank.&nbsp;&nbsp;If the city and state are not blank, they need to be varified by the above explaination.<br><br>How can I code this?&nbsp;&nbsp;I am a fairly new JavaScript user and my brain is fried!<br><br>Thanks!
 
Dear angela,<br><br>I tested this is IE 4 and 5 and nutscrap 4.06.<br><br>Hope this helps<br>-pete<br><br>function form1_onsubmit() {<br><br> var sCity = document.form1.city.value;<br> var sState = document.form1.state.value;<br> var sZip = document.form1.zip.value;<br> <br> // City, State, Zip valid flags<br> var validFlags = new Array(false,false,false);<br> <br> // matches 5 digits<br> var re = new RegExp(&quot;^([0-9]{5})$&quot;);<br><br> // see if zip matches 're'<br> validFlags[2] = ( 0 == sZip.search(re))<br> <br> <br> // if zip is not valid check '##### ####'<br> if ( !validFlags[2]){<br> // matches 5 digits space 4 digits<br> re = new RegExp(&quot;^([0-9]{5} [0-9]{4})$&quot;);<br> validFlags[2] = ( 0 == sZip.search(re));<br> }<br> <br> if ( validFlags[2]){<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// city and state can be empty<br> if ( 0 == sCity.length)<br> validFlags[0] = true;<br> if ( 0 == sState.length)<br> validFlags[1] = true;<br> }<br> <br> if ( !validFlags[0]){ // City<br> <br> re = new RegExp(&quot;^([a-zA-Z]{3,})$&quot;);<br> validFlags[0] = ( 0 == sCity.search(re));<br> }<br> <br> if ( !validFlags[1] ){ // State<br> <br> re = new RegExp(&quot;^([a-zA-Z]{2})$&quot;);<br> validFlags[1] = (0 == sState.search(re));<br> }<br> <br> if (!validFlags[0] ¦¦ !validFlags[1] ¦¦ !validFlags[2])<br> alert(&quot;not valid&quot;);<br> <br> return validFlags[0] &&<br> validFlags[1] &&<br> validFlags[2];<br>}<br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top