Extra 10-1 Use JavaScript to validate a form In this exercise, you’ll use JavaSc
ID: 3917814 • Letter: E
Question
Extra 10-1 Use JavaScript to validate a form In this exercise, you’ll use JavaScript to validate a reservation request form.
1. Open the index.html and reservation.js files in this folder: exercises_extrach10 eservation Then, run the application and click the Submit Request button to see the page that’s displayed when the form is submitted to the server.
2. In the JavaScript file, notice that the ready event handler contains the declaration for a variable named emailPattern that contains the pattern that will be used to validate the email address.
3. Code a statement that moves the focus to the Arrival date text box.
4. Code an event handler for the submit event of the form. This event handler should validate the user entries and cancel the submission of the form if any of the entries are invalid. The validation is as follows:
A value must be entered into each text box.
The number of nights must be numeric.
The email address must match the pattern that’s provided.
Be sure to trim the entries and put them back into the controls regardless of whether the entries are valid.
index.html
reservation.js
Explanation / Answer
The reservation.js code is as follows...
If you need any further explanation on the code, drop your query in the comments
reservation.js:
$(document).ready(function() {
var emailPattern = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}/;
var datePattern =/^([0-9]{1,2})/([0-9]{1,2})/([0-9]{2,4})$/;
var email,no_of_nights,phone_no,date;
/* If Submit is clicked then validate below conditions */
$("#submit").click(function(){
email = $("#email").val();
no_of_nights = $("#nights").val();
phone_no = $("#phone").val();
date = $("#arrival_date").val();
/* Check if date is valid */
if(!(datePattern.test(date))){
alert("Invalid Date");
document.getElementById('arrival_date').value = ""; // clear the textbox
$('#arrival_date').focus(); // focus the textbox
}
else if(isNaN(no_of_nights)){ // isNAN checks whether input is a number or not
alert("Nights should be Numeric");
document.getElementById('nights').value = "";
$('#nights').focus();
}
else if(!(emailPattern.test(email))){
alert("Invalid Email");
document.getElementById('email').value = "";
$('#email').focus();
}
else if(isNaN(phone_no)){
alert("Phone No. should be Numeric");
document.getElementById('phone').value = "";
$('#phone').focus();
}
});
}); // end ready
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.