Get latest news and Web Designing tutoria

Thursday 4 June 2015

Javascript Form Validation - the email function

We'll start with the function that checks the email address text box. We'll only check if the text box has had anything typed into it. Checking for a correct email address is notoriously difficult, so we're just trying to keep things simple here.
Add the following function to your code (you won't be able to copy and paste because ours is an image - you'll learn more if you type it out for yourself):

A check email function


Your script tags should now look like this:

The email and validate functions

The first line of the checkEmail function is this:
var email = document.frmOne.email.value;

document.form_name.element_name.element_value
Our form was called frmOne, so we start with document.frmOne. The element name you're trying to access comes next. In the HTML, we gave our text box element the name email. If you want to get what was in the text box, you need the value attribute at the end.
So we're getting the text value from the text box and storing it in a variable called email.
The IF statement tests what is in this variable. We're only testing for a blank value (two double quotes with no spaces between them, though you can single quotes instead of doubles). If email is blank then two things happen:
document.getElementById("email_error").innerHTML = "No Email Address";
return false;
We're using getElementById to access an HTML element with the ID "email_error". Notice that we're also using innerHTML after getElementById. The inner HTML is anything between two tags. So if you had <P>Some inner text</P> then the innerHTML would be "Some inner text". After an equal sign we're resetting the innerHTML and replacing it with the text "No Email Address".
The next line is return false. This is enough to set the whole of the function to false.
If the text box is not blank we set the innerHTML again, this time to a blank string. The return value is then true.
You can try your script out now. Don't type anything in the email text box. Just click the submit button. You should see this:

Email error message
Now type something in the text box. Click the submit button again and the red error message should go away.

0 comments:

Post a Comment