Introduction
This is a short and simple form validation code that uses regular expression to compare the user input to the pattern rule defined by a regular expression string. form validation code will either use "if" statments, or regular expressions to validate that the user entered the currect information .
The main difference between this code and others , is that the regular expression pattern, and the error message, both are located inside the html control tag and not in the function itself. The advantage is that you don't need to mess with the function to change a specific condition or validation rule, you simply need to enter the rule in the html tag under the validate attribute. The disadvantage is redundancy, if you have three fields in a form that needs to implement the same rule, you will still need to rewrite the regular expression on each of those control. I hate redundancy as everybody else, but I think that in this particular code it is not a high price to pay for a generic function.
The Code
The function goes over the form elements searching for a "validate" attribute and tries to mach the regular expression value of the attribute with the user input. If the user input doesn't comply with the regular expression pattern the function will raise an error alert. In other words, the content of each form-element with the attribute "validate" will be evaluate by the function to check if it follows the regular expression rules
- The function receives the from as an object.
function checkForm(formObj){ - The variable msg is initialized to an empty string. Any data not matching the regular expression will invoke the code to collect the error description into this variable. So all the errors on the form will be presented to the user together in one alert rather then separate alerts for each error.
var msg=""; - Loop through the form elements.
for (var i=0; i < formObj.elements.length; i++) { - Check if the element has a name, and a validate attribute.
if (formObj.elements[i].name !=null && formObj.elements[i].getAttribute("validate")){ - Evaluate the regular expression from the element validate attribute.
var validationRule = eval(formObj.elements[i].getAttribute("validate")); - If a mismatch was found, then add the error description from the control tag validateMsg attribute to the msg variable.
if (!validationRule.test(formObj.elements[i].value))
var obj = formObj.elements[i].parentNode; // add a * mark on the validate field – this part is not mandatory and can be removed.
if (obj.nodeName=="TD")
{ obj.innerHTML = "!!!"+ obj.innerHTML; }
msg += formObj.elements[i].getAttribute("validateMsg")+"\n";
!! end the loop - If the msg variable is not empty it means that errors were found. Present the errors and return false.
if (msg.length > 0){ alert (msg); return false; } else{ return true; }
function checkForm(formObj){
var msg="";
for (var i=0; i < formObj.elements.length; i++) {
if (formObj.elements[i].name !=null &&
formObj.elements[i].getAttribute("validate")){
var validationRule =
eval(formObj.elements[i].getAttribute("validate"));
if (!validationRule.test(formObj.elements[i].value)){
var obj = formObj.elements[i].parentNode;
if (obj.nodeName=="TD")
obj.innerHTML =
"<span style='color:red;'>!!!</span>"+ obj.innerHTML;
msg += formObj.elements[i].getAttribute("validateMsg")+"\n";
}
}
}
if (msg.length > 0){
alert (msg);
return false;
}
else{
return true;
}
}
Code Implementation
In order to use the code follow these steps:
- Copy the code to your page between the <script></script> tags or create a JS file and link it to your HTML page.
- In the form tag add the method to the onclick event: <form method=post name=myForm onsubmit="return checkForm(this);">
- At each html control you would like to validate add the validate attributes and the errDescription attributes: <input width=100 type=text validate="/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/" name=email id=email validateMsg="not the right format">
Some regular expressions:
- validate="/[\d\w]{3,}/" - the data must be at least 3 characters long and should include letters or digits
- validate="/^([0-9]{11})$/ " - Phone number with 11 digits.
- validate="^([0-9]){2}(\/|-){1}([0-9]){2}(\/|-){1}([0-9]){4}$/" – Date in the format dd/mm/yyyy
- validate="/^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/" – Email