Details about form verification in JavaScript, and details about javascript forms
Form Verification occurs on the server. The client has entered all necessary data and then pressed the submit button. If some input client data has been lost in an incorrect format or simply, the server sends all required data back to the client, and resubmit the request in the form of correct information. This is a long process that will increase the burden on the server.
JavaScript provides a way to verify data on the client's computer before sending it to the web server. Form Verification is usually performed in two ways.
- Basic verification-first, the table must be checked to ensure that each of its form fields is required for data input. This will only need to loop through each field in the table and check the data.
- Data format verification-second, the entered data must be checked for correct format and value. This requires more logic to test data correctness.
Let's take an example to understand the verification process. The following is a simple form:
Basic Form Verification:
First, we will show you how to perform a basic form verification. In the preceding table, The validate () function is required to verify that data occurs in the onsubmit event. The following is the implementation of the validate () function:
<script type="text/javascript"><!--// Form validation code will come here.function validate(){ if( document.myForm.Name.value == "" ) { alert( "Please provide your name!" ); document.myForm.Name.focus() ; return false; } if( document.myForm.EMail.value == "" ) { alert( "Please provide your Email!" ); document.myForm.EMail.focus() ; return false; } if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) || document.myForm.Zip.value.length != 5 ) { alert( "Please provide a zip in the format #####." ); document.myForm.Zip.focus() ; return false; } if( document.myForm.Country.value == "-1" ) { alert( "Please provide your country!" ); return false; } return( true );}//--></script>
Data format Verification:
Now we will see how we can verify the input form data before submitting it to the Web server.
This example shows how to verify the entered email address, which means that the email address must contain at least one @ symbol and one dot (.). In addition, @ must not be the first character of the email address. The last point must be a character after the @ symbol:
<script type="text/javascript"><!--function validateEmail(){ var emailID = document.myForm.EMail.value; atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if (atpos < 1 || ( dotpos - atpos < 2 )) { alert("Please enter correct email ID") document.myForm.EMail.focus() ; return false; } return( true );}//--></script>