Check the following code
Code:
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
function trim(str){
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function checkform(){
// First the normal form validation
if (trim(document.form.user.value) == '') {
alert('[Please complete the "required" field]');
document.form.user.focus();
return false;
}else if (trim(document.form.user.value).length < 7) {
alert('User name length should be greater than 6');
document.form.user.focus();
return false;
}
if (trim(document.form.pass.value) == '') {
alert('Please complete the "required" field');
document.form.pass.focus();
return false;
}else if(trim(document.form.pass.value).length < 7){
alert('Please enter a password with a length not less than 7');
document.form.pass.focus();
return false
}
if (trim(document.form.mail.value) == '') {
alert('Please complete the "required" field');
document.form.mail.focus();
return false;
}else if (!validateEmail(document.form.mail.value)) {
alert('Please enter a valid email ID');
document.form.mail.focus();
return false
}
if (trim(document.form.passr.value) == '') {
alert('Please complete the "required" field');
document.form.passr.focus();
return false;
}
if (trim(document.form.dis.value) == '') {
alert('Please enter image');
document.form.dis.value = '';
document.form.dis.focus();
return false;
}
return true;
}
In the above code I've introduced two JavaScript function one for validating email ID and another one for trimming a string (removing empty space from left and right side of a string). I've also changed your code a bit so that if the user enters space character in the form fields you can avoid it while validating the inputs.
Bookmarks