Validation with forms & JavaScript
Create message and noerrors variables
Inside our function, add the following code:
function userinformation(form){
var message="Please complete the following: \n\n";
var noerrors=message;
}
First, we declare two variables, message and noerrors by using the var keyword. We assign our message variable a text string informing our visitor what they need to complete. We set noerrors variable to the value of message. As mentioned before, we’ll use a simple conditional check to determine the following:
- If message is equal to noerrors, we do nothing
- If message is not equal to noerrors we show an error dialog
We use a character escape sequence common to C derivative languages, \n, which causes a new line for each error which occurs.
Validate first name field
We check the value of the first name field for a value by adding the following code:
function userinformation(form){
var message="Please complete the following: \n\n";
var noerrors=message;
if(document.contact.fname.value==""){
message+="Please enter your first name: John\n";
}
if(message==noerrors){
return true;
}else{
alert(message);
return false;
}
}
In the conditional statement, we do the following:
- Check the value of the first name field (fname):
- If it’s equal to a null string:
- We assign and concatenate our message variable with an error message, followed by a new line
We can use shorthand syntax for the error message variable (+=) to keep our code more readable. The equivalent is:
message=message + "Please enter your first name: John\n";
Save your JavaScript file and preview the results.
Validate last name field
We check the value of the last name field for a value by adding the following code:
function userinformation(form){
var message="Please complete the following: \n\n";
var noerrors=message;
if(document.contact.fname.value==""){
message+="Please enter your first name: John\n"; }
if(document.contact.lname.value==""){
message+="Please enter your last name: Doe\n
}
if(message==noerrors){
return true; }else{
alert(message);
return false;
}
}
In the conditional statement, we do the following:
- Check the value of the last name field (lname):
- If it’s equal to a null string:
- We assign and concatenate our message variable with an error message, followed by a new line
Save your file and preview the results.
We'll continue with validating check boxes next.