Javascript Form Checking
Javascript Form Checking
A very popular use for JavaScript is its ability to check input data from forms before we send it to the server to be processed (added to a database, email, etc.)
What we will be doing is creating a simple HTML/CSS contact form, getting very basic information about the user. Use the code below in your body tags to create the html part of our form:
<div class="contact_form">
<form>
<fieldset>
<legend>Email Us</legend>
<div>
<label>Your Name</label>
<input type="text" name="your_name" value="" />
</div>
<div>
<label>Email Address</label>
<input type="text" name="email" value="" />
<small>Please enter a valid email address</small> </div>
<div>
<label>Message</label>
<textarea name="message"></textarea>
</div>
</fieldset>
<input type="submit" value="Send Email" />
</form>
</div>Followed by our CSS code here (You can either add this in a new style sheet or included in style tags in the head of your document):
.contact_form {
margin: 10px;
padding: 5px;
background-color: #FFF;
border: #EEE 1px solid;
}
.contact_form form fieldset {
margin: 10px 0px 10px 0px;
padding: 10px;
border: #DDDDDD 1px solid;
}
.contact_form form legend {
font-weight: bold;
color: #7898c2;
font-size:15px;
}
.contact_form form fieldset div {
padding: 4px 0px 4px 0px;
}
.contact_form label{
margin-right: 10px;
padding-right: 10px;
width: 150px;
display: block;
float: left;
text-align: right;
font-weight:bold;
font-size: 14px;
}
.contact_form form small {
margin-left: 170px;
display:block;
font-size: 10px;
color: #333;
}All of the above should be pretty familiar. If you are having trouble with anything be sure to go back and read the HTML / CSS Forms article.
So now on our page we have three nice looking fields: Name, Email Address, and Message. What we want javascript to do is call a function when we press the submit button, what that function will do is check to verify that all fields are correct and the form can be submitted.
When setting up, especially for beginners, it is a good idea to test and make sure that your functions and variables are being called and set correctly before you go to far along in your code. This way, problems are easier to debug. Let's start with our function, and the code in it will just let us know when the code is run. In the head of your document, add your script tags and function:
<script type="text/javascript">
function checkform(){
alert("Function Called");
}
</script>So we set up the function named checkform but it won't do anything yet. We need a way to call it once the form is submitted. Luckily there is an attribute of the form tag called "onSubmit", it lets us run javascript once the submit button is clicked. Add the attribute that will call this function to your form tag:
<form onsubmit="checkform()">
Test out your page, fill in some content then click the submit button. Most likely the alert will come up, and then the form will submit, refreshing the page and fields. What we need to do is prevent this form from submitting until we decide it is ready. To do that, we will be using a javascript "return". What a return does in javascript is exits a particular function and returns a specific value (in our case either true or false). This should make a little more sense once we see it in action. First, let's get our form ready to accept our return value, add "return " before the function is called:
<form onsubmit="return checkform()">
This just lets the form know that the checkform function will be returning a value. If that value id true, the form will be submitted. If the value is false, it will not. Now we can return false at the end of our function and our form should not submit:
function checkform(){
alert("Function Called");
return false;
}Test this out, what you should notice is that when you fill out the form and click submit, the alert will pop up, but afterwards the data should not be submitted. You can change this value to 'true' to see the opposite effect. Also try moving the return above the alert line. Once the return is called it exists the function, so the alert would never be called.
Now that we have the general structure of our function ready, let's take a look at how we can check the data of forms on the page. We will what's called 'dot syntax' to target the specific item we want. We have used this before when we used document.write(), we were calling the write() method of the document object. So if we want to target a form, it will look something like "document.FORMNAME.FIELDNAME". Problem is we haven't given our form a name yet, so let's do it.
<form name="myform" onsubmit="return checkform()">
So we will be referencing the form as "myform". This is also a good time to double check that each of your form fields have a name. The should be named as "your_name", "email", and "message". Now that everything is named, we can test it out. Replace the alert statement in your function with the following:
alert(document.myform.your_name.value);
We are alerting the value of the "your_name" field which is in the "myform" object, which is in the "document" object. A lot of items inside of items but the more you use this method the more you will make sense of it. Test out your page, fill something in the name field and click submit. It should pop up whatever value you type in.
Now, with an understanding of how to obtain these values, we can use an if statement to check that the value is not blank:
function checkform(){
if(document.myform.your_name.value == ""){
alert("Please fill out your name");
}
return false;
}So now, test out your page again and don't fill anything in, if since your value is empty it should give you an error and tell you to fill some text into the field. We can then use an advanced if/else statement to verify that all fields are filled out:
function checkform(){
if(document.myform.your_name.value == ""){
alert("Please fill out your name");
}else if(document.myform.email.value == ""){
alert("Please fill out your email address");
}else if(document.myform.message.value == ""){
alert("Please fill out a message");
}
return false;
}This is almost where we want to be. We check to make sure each field is not empty, but before we setup our returns to make sure the form submits when it should, let's take a look at two javascript methods we can use to verify data as well:
indexOf(): What this method will do is return the first index of a specific character. By index I am referring to the position of a string. Let's imagine the text "Hello World!", including the space in between the words and the exclimation mark, the string has 12 characters in it. The tricky part is the index will always start at 0. H being 0, e being 1, l being 2, and so on. So if I wanted to know the index of the character "W", the index would be 6. The way we would write this in javascript is (assuming mystring is a variable containing "Hello World"): mystring.indexOf("W"); and this value would equal 6.
The important thing here is that if the character "W" is not found in the string, the result will be -1. So we can check to see if a character exists in a string or not by checking to see if it is or is not -1.
charAt(): This is very similar to indexOf and has the opposite effect. We can tell charAt to look for the index at 3 and it will find whatever the 4th character in our string is (remember, the index starts at 0). So from our previous example, mystring.charAt(6) will equal "W".
With that knowlege, let's use the indexOf method to verify the user submitted a correct email address. We will also fix the returns in our function:
function checkform(){
if(document.myform.your_name.value == ""){
alert("Please fill out your name");
return false;
}else if(document.myform.email.value == ""){
alert("Please fill out your email address");
return false;
}else if(document.myform.message.value == ""){
alert("Please fill out a message");
return false;
}else if(document.myform.email.value.indexOf("@") == -1 || document.myform.email.value.indexOf(".") == -1){
alert("Please enter a valid email address");
return false;
}
return true;
}
We added one new if statement here, notice we used the || operator (Hold shft+\) to tell the if statement that if either of the two statements are true, then run the alert. So the statement basically reads:
"If the email does not contain an @ symbol OR the email does not contain a . give an error"
We check for this because we know all email addresses contain a period and an @ symbol.
We also made sure that after each alert we added return false. This makes sure if there is an error, theform will not send. Finally make sure the last return outside the if statement is true. If all fields are correct, the form submits.








Comments
Post new comment