Javascript Tutorials
Introduction to AJAX
Javascript Form Validation
Javascript Fundamentals

Javascript Form Validation

Javascript Check Field Functions

Check Form Field Has Value

function formNotEmpty(elem) {

var field = elem.value;

if (field.length == 0) {
return false;
} else {
return true;
}
}

The function formNotEmpty(elem) checks the field value passed into the function in the elem variable. We set the variable field to the value of the field passed in the elem variable. The if statement checks the length of field and if its equal to 0 false is returned if the length is longer than 0 true is returned.

Javascript Email Validation Regex Check

function formIsEmail(elem) {

var field = elem.value;

var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+.)+([A-Za-z][A-Za-z]|[A-Za-z][A-Za-z]
[A-Za-z])|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
return regex.test(field);
}

Here in formIsEmail(elem) we check the value of the field passed against a regex. We set regex to a regular expression that verifies a valid email address. We return the test of the field value. Performing .test against a variable set to a regex will return true or false based on the value matching. If you wanted to get hardcore with email checking you could replace ([A-Za-z][A-Za-z]|[A-Za-z][A-Za-z][A-Za-z]) with a regex containing all the top level domains.

Javascript Error Alert Function

function orderFormErrors(errorNumber) {

switch(errorNumber) {
case 0:
return "Please enter your name";
break;
case 1:
return "Please enter a valid EMail";
break;
case 2:
return "Please enter a message";
break;
case 3:
return "Please don't use bad words";
break;
}
}

This function stores our error messages. We pass it the number of the check the failure was on. A simple switch statement determines which message to display.

Getting Started With Javascript Validation <<  1 2
New Content