midwest web design

Client side validation w/forms

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:

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:

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.

See form 1

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:

Save your file and preview the results.

See form 2

We'll continue with validating check boxes next.

top of page

Thank you for visiting Midwest Web Design.net - Come back again soon.