I'm creating a form where users enter their address (not all shown on the code) and their postcode. If it is a UK postcode I need to make sure it conforms to UK postcode standards, so I have a series of regular expressions. Users are asked to check a radio button to say whether their address is uk or other.
At the moment I've got the code so it will always be validated against the regular expressions, but I need it to only do this if the UK option is checked. I have tried to do this but am failing badly!
Can anyone help me?
Thank you in advance!!
At the moment I've got the code so it will always be validated against the regular expressions, but I need it to only do this if the UK option is checked. I have tried to do this but am failing badly!
Can anyone help me?
Thank you in advance!!
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Address Validation</title>
<script language="javascript" type="text/javascript">
<!-- Hide script from older browsers
re1 = /^([^qvxQVX][^ijzIJZ]?\d\d?)[\.\-\/\s]?(\d[^cikmovCIKMOV]{2})$/
re2 = /^([^qvxQVX]\d[abehmnprvwxyABEHMNPRVWXY])[\.\-\/\s]?(\d[^cikmovCIKMOV]{2})$/
re3 = /^([^qvxQVX][^ijzIJZ]\d[abcdefghjkstuwABCDEFGHJKSTUW])[\.\-\/\s]?(\d[^cikmovCIKMOV]{2})$/
re4 = /^([gG][iI][rR])[\.\-\/\s]?(0[aA]{2})$/
function submitIt(myForm) {
countryOption = -1
for (i=0; i<myForm.country.length; i++) {
if (myForm.country[i].checked){
countryOption = i
}
}
if (countryOption == -1) {
alert("Please select UK or other")
return false
}
if (validPCode = re1.exec(myForm.pCode.value)){
myForm.pCode.value = validPCode[1] + " " + validPCode[2]
}
else if (validPCode = re2.exec(myForm.pCode.value)) {
myForm.pCode.value = validPCode[1] + " " + validPCode[2]
}
else if (validPCode = re3.exec(myForm.pCode.value)) {
myForm.pCode.value = validPCode[1] + " " + validPCode[2]
}
else if (validPCode = re4.exec(myForm.pCode.value)){
myForm.pCode.value = validPCode[1] + " " + validPCode[2]
}
else{
alert(myForm.pCode.value + " is an invalid UK postcode")
myForm.pCode.focus()
myForm.pCode.select()
return false
}
}
// End hiding script -->
</script>
</head>
<h2 align="center">Address Validation</h2>
<form onsubmit="return submitIt(this)" action="someAction.cgi" name="myForm">
<table border="0" cellspacing="8" cellpadding="8">
<tr>
<td align="right" valign="top">
Postcode <input name="pCode" type="text" size="25" /> Country: <input type="radio" value="UK" name="country" />UK <input type="radio" value="other" name="country" />Other
</td>
<td>
<p><input type="reset"/> <input type="submit" value="Submit" /></p>
</td>
</tr>
</table>
</form>
<body>
</body>
</html>