Write JS code to validate the following fields of a form
- phone number (format: xxx-xxx-xxxx )
- zip code (format: xxxxx-xxxx)
Solution
- phone number (format: xxx-xxx-xxxx )
- zip code (format: xxxxx-xxxx)
Solution
<html>
<head>
<script type="text/javascript">
var validateForm = function() {
validatePhone();
validateZipCode();
}
var validatePhone = function() {
var phoneRegexp = /^\d{3}-\d{3}-\d{4}$/;
var phoneTest = phoneRegexp.test(document.myForm["phone"].value);
if (phoneTest == false) {
alert("Please enter correct phone number in the format xxx-xxx-xxxx");
return false;
}
}
var validateZipCode = function() {
var zipcodeRegexp = /^\d{5}-\d{4}$/;
var zipTest = zipcodeRegexp.test(document.myForm["zip"].value);
if (zipTest == false) {
alert("Please enter Zip Code in the format xxxxx-xxxx");
return false;
}
}
window.onload = function() {
document.getElementById("Form").onsubmit=validateForm;
}
</script>
</head>
<body>
<form name="myForm" id="Form" method="post" action="#">
Phone<br/>
<input type="text" name="phone" id="phoneField"/> <br/>
Zip Code<br/>
<input type="text" name="zip"/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
No comments:
Post a Comment