The "Freeola Customer Forum" forum, which includes Retro Game Reviews, has been archived and is now read-only. You cannot post here or create a new thread or review on this forum.
[B][U]Basic validation of your HTML web form, client-side, using JavaScript[/U][/B]
HTML web forms allow web users to submit information to the web site directly, whether it be for a search query, online order, forum post or general feedback. The problem is that some web users don’t fill in the form fields in the way that the web site owner would have liked. This is why web form validation is often used on many websites.
There are two types of validation, “client-side” and “server-side”.
Client-side validation
Client-side validation is performed by the users web browser, such as Internet Explorer, Firefox or Safari, using a web scripting language, such as JavaScript. This is done without the web page having to be reloaded, and so can provide instant feedback to the user when a problem with their entered information is detected.
Using client-side validation can speed up the entire process for the end user (the person filling in the web form) and encourage them to send information that you can easily make use of. The downside being that if JavaScript is disabled or not otherwise available, the validation will be completely ignored.
Server-side validation
Server-side validation is performed on the web site server, meaning the web page needs to be sent in order for the validation to take place. If a problem is detected, the web server must then send back another web page, alerting the user to the problem, and asking them to submit again.
The benefit of server-side validation is that even if the user has JavaScript turned off, the validation can still take place. Freeola’s Form to Mail script contains limited server-side validation (if you require it).
While this is a guide to using JavaScript to validate a web form, it is important to note that client-side validation should not be considered a replacement for server-side validation, but rather a complimentary addition to it. The benefit will be to the end user, who can receive instant notification of any incorrectly entered or missing information.
While JavaScript is not the only web scripting language available, it is the most widely adopted, with all major web browser’s supporting it to a degree. It is for this reason that you should use JavaScript for client-side validation, as opposed to, say, VBScript, which is currently only available to the Internet Explorer web browser.
It should also be noted that this is a pretty basic guide to getting started with validating a web form using JavaScript, and won’t cover every available option at your disposal. It is also assumed that the reader has a basic grasp of HTML, and can create an HTML web form.
The methods used below are also not exclusive to the examples provided. You don’t only have to use the matching example for passwords, or the no empty field example for someone’s name.
Getting started
Each of your HTML form controls should contain the
name
attribute, which you will need to have on hand when putting together your validation code. Referencing these name
values will be done via the form
object model, which is built-in to web browsers.If your form controls do not contain
name
attributes, you can still refer to them in the order that they appear, but this might be a little tricky if you’re just starting out.JavaScript can be reference to either internally within the HTML web page, or in a separate file. Which method you choose is down to you, although you should use an external file if your scripts will be used by more than one web page.
Below is a simple example of how to apply JavaScript to your html page.
Internal example:
External example:
Whichever method you choose, the JavaScript validation code will be enclosed in a function called
validate
. To make the web browser use this JavaScript function, you will need to add the code onsubmit="return validate(this);"
to your HTML <form>
element, for example:
<form method="post" action="form-catch.php" [B]onsubmit="return validate(this);"[/B]>
This tells the web browser that if JavaScript is supported, if should check with the function
validate
before it actually submitted the form. The function will then run the validation code, and tell the web browser if it can submit or not.The code that appears within the
validate
function will be your own, and how the final code looks will all depend on what type of validation you require. The base code is listed below, which you’ll need to copy and paste in to your web page or external JavaScript file.
function validate(f) {
[U]// JavaScript validation code goes here.[/U]
return true;
}
The underline text // JavaScript validation code goes here. will need to be deleted, and replaced with your own code.
The code
return true;
must be the last bit of code, as this is the OK given to the web browser if the form validation is completed, and no problems are found. Throughout the script, you’ll use the code return false;
that tells the web browser to stop because a problem was found, and that it should not submit the form until the validation code has been run again.With that out of the way, lets get right in to some examples that you may make use of.
No empty form fields please!
Probably the most common form control used is the single input box, which allows a user to enter a line of text. This is usually their username, first name, email address, etc. Often, these will be marked as being required, in that they can’t be left blank.
To check if field is empty, you can use the code
if (f.firstname.value == 0)
, which basically means “if this field equals nothing”. This doesn’t just cater to missed out fields, but also those that a user may just have pressed the spacebar, resulting in 3 or 4 blank spaces.The
f
in the code is the reference to the current form that the user is filling in, while the firstname
is the actual value within the name
attribute of the input element. In this case, the above code refers to the HTML element <input type="text" name="[B]firstname[/B]">
. The value
is a property of the HTML element, which refers to the actual text entered by the user (for example, this could be “John”). Each of these must be separated with a period (full stop, or dot), but no spaces.Below is the code that will check for and alert the user if they have forgotten to enter their first name. The code first checks if a value exists, and will ignore the block of code between the curly brackets ({ }) if a name was entered. If a name wasn’t entered, then the code within the curly brackets ({ }) is executed.
In this case, the code would first alert box the user that there was a problem:
-
alert("Please enter your first name.");
Then, reset the field to be empty, removing any spaces that may have appeared.
-
f.firstname.value = "";
Then, set the focus to the element that was not filled in correctly:
-
f.firstname.focus();
Finally, the JavaScript code would end, and the form would not be allowed to submit:
-
return false;
This would then allow the user the opportunity to fill in the information that was being asked of them.
As mentioned above, the validation code needs to appear within the
validate
JavaScript function. If you were to use the example form validation mentioned above, the whole JavaScript code you would need may look like this:
function validate(f) {
// Validate first name.
if (f.firstname.value == 0) {
alert("Please enter your first name.");
f.firstname.value = "";
f.firstname.focus();
return false;
}
return true;
}
To apply the validation to the next form field, you would need to make a copy and paste of the code, and change it to refer to the form field as required, for example:
if (f.[B]last[/B]name.value == 0) {
alert("Please enter your [B]last[/B] name.");
f.[B]last[/B]name.value = "";
f.[B]last[/B]name.focus();
return false;
}
The above code sample isn’t exclusive to the single input box form control, and can be used for the or controls also.
Correctly formatted email address
Asking the user for an email address is a common thing to do, otherwise it’ll be pretty difficult to reply to them if need be. While JavaScript can’t ensure the email address entered is correct, or even real, you can use it to ensure the address is formatted in the anticipated manor. This can be done using a regular expression, which in this example, is written like so:
var emailregex = [B] /^[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*
(SPACE) @[a-zA-Z0-9]+([\.]?[a-zA-Z0-9]+)*
(SPACE) ([-]?([a-zA-Z0-9-]+[a-zA-z0-9]+))*
(SPACE) (\.[a-zA-Z]{2,4})+$/ [/B];
You will need to remove the “(SPACE)” bit, as this was added due to Freeola limitations on the web forum.
Pardon me?
Naturally, the regular expression will look like a mess to most people, but what it does is break up the users email address in to two parts (before and after the @ symbol), and check that both parts are set out as expected, which are:
- The first part contains only letters, numbers, dashes or dots, up to the point of the @ symbol. A dash or a dot doesn’t necessarily have to be there, but can be as they are valid within an email address, but can’t be the first or last character. The part before the @ symbol can’t be blank (meaning the @ can’t be the first character) but doesn’t have a set limit to the number of characters that can appear.
- The @ symbol actually exists within the entered email address, but only once, and not as the first or last character.
- The second part contains only letters, numbers, dashes or dots, after the @ symbol. At least one dot must appear, which is then followed by either two, three or four letters (that represent .com, .info, .co.uk, etc). It cannot begin or end with a dot.
The variable
emailregex
contains the regular expression, and to use it requires the test
function, which is built-in to JavaScript.In this example, you should assume that the HTML form control has been given a
name
attribute of email, such as
.Don’t forget, you will need to remove the “(SPACE)” bit, as this was added due to Freeola limitations on the web forum.
var emailregex = /^[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*
(SPACE) @[a-zA-Z0-9]+([\.]?[a-zA-Z0-9]+)*
(SPACE) ([-]?([a-zA-Z0-9-]+[a-zA-z0-9]+))*
(SPACE) (\.[a-zA-Z]{2,4})+$/;
if (!emailregex.test(f.[B]email[/B].value)) {
alert("[B]Please enter a valid email address.[/B]");
f.[B]email[/B].value = "";
f.[B]email[/B].focus();
return false;
}
The
test
will check the email address entered by the user, and if it does not match the rules from the regular expression, will cause the fail to trigger, which will result in the same effect as the previous example, only with a different error message.Did they match?
When signing up to a web site that requires a username or password for an account holder, you’ll often be asked to re-type in you desired password. This is done to check that the user didn’t tap a letter or number incorrectly while originally entering their choice. Had the user only been asked once, they could believe they’ve typed in “myPassWord”, when in actual fact they didn’t press the shift key the first time, and actually typed in “mypassWord”. If this had not been checked, the password set for the new account would not be the one the user thought they typed, and so they would not be able to use their new account, without having to use a “forgotten password” function of the web site.
The code used for this is a basic “does this match that”, although as we want to only alert the user if the two password form controls don’t match, the code is reversed to read as “does this value not equal that value”, which for our HTML form would be written in JavaScript as
[U]f.password.value[/U] [B]!=[/B] [U]f.passwordconfirm.value[/U]
.Placing that within the
if
statements and adding the relevant alert message would give you JavaScript code that looks like this:
But won’t JavaScript see the asterisk (*) characters, like me?
No, because the asterisk (*) characters that appear in an field is only a visual deterrent from people overlooking your shoulder. The web browser and JavaScript will see the correct characters, as written by the user, and won’t see a string of asterisks for each field and consider it valid.
Did they tick the checkbox?
The checkbox is a simple form control, you either tick it, or you don’t. Validating it will not usually be required, as it is generally used as the “optional” selection method.
Checking to see if it has been selected is simply a case of seeing if the
checked
property is not set to true, like so:
if ([B]![/B]f.tandc.checked) {
alert("Please indicate that you have read and accepted our terms and conditions.");
f.tandc.focus();
return false;
}
If the checkbox isn’t ticked, the form is prevented from submitting, and the alert appears. The checkbox will also receive the focus, allowing the user to quickly selected it.
Bullet points everywhere, but not a single hit!
Validating a bullet point (or radio) selection list is a little trickier, because by definition the radio list HTML code needs to have the same
name
attribute to define group correctly, for example:
<input type="radio" [B]name="[I]gender[/I]"[/B] value="female">Female
<input type="radio" [B]name="[I]gender[/I]"[/B] value="male">Male
To validate a radio list, you need to use JavaScript to check each radio button individually, to see if any of them has been selected. The code below will do this for you. It first creates a variable to keep a note of when one selection is found, and then loops through all the radio button, checking for the
checked
property. If one of the radio buttons is found to have been selected, the variable value changes from FALSE
to TRUE
, if not, the value stays at FALSE
.
var genderselected = "FALSE";
for (i=0;i<f.gender.length;i++) {
if (f.gender[[U](SPACE)[/U]i].checked) {
var genderselected = "TRUE";
}
}
You will need to remove the “(SPACE)” bit, as this was added due to Freeola limitations on the web forum.
We then check to see if the value of our
genderselected
variable is still set to FALSE
. If it is, it means the user has not made a selection from this radio list, and so the form is prevented from submitting, and an alert is displayed as required.
if (genderselected == "FALSE") {
alert("Please select your gender.");
f.gender[B][0][/B].focus();
return false;
}
Because JavaScript considers a radio button list an array, you’ll need to tell the browser which radio button you wish to set the focus on if the alert is triggered.
[B][0][/B]
means the first button, [B][1][/B]
would be the second, and so on. Setting the number to high will result in an error, and may even cause the entire validation function to fail.Why validate, why not just default (pre-select)?
HTML web forms allow for selectable elements (such as the radio button, checkbox or drop down menu) to be pre-selected for the user. The problem with this is when the pre-selected option differs from what the user may have selected, but isn’t noticed.
For example, if a user was asked to select their gender, and female was the pre-selected option, a user could submit the form without noticing the incorrect selection. Because the validation only checks that an option is selected, it sees no reason to alert the user.
Replace an alert box with an input prompt box.
While the alert box is a viable method for alerting the user to a problem, a prompt box will not only alert the user, but will allow them to enter a line of text at the same time. This type of box is only suitable for text input fields, and not really for radio buttons, checkboxes or selection lists.
The code to generate a prompt box differs slightly, as not only does it allow you to provide your alert text, it also allow you to pre-set a text value in the input area, as show below:
prompt("Alert text goes here","Pre-entered text goes here");
If you don’t want to set any pre-entered text for the user, you should leave the second set of quotation marks empty. If you delete them altogether, Internet Explorer will use the text “undefined”, which may look out of place, or confuse the user as to what it means.
To make use of the prompt box, you will need to alter your code slightly. The prompt box needs to be applied to the input field directly, so when the user enters the text, it’ll appear in the required field automatically.
if (f.name.value.length == 0) {
[B]f.name.value[/B] = [B]prompt("[I]Please enter your name.[/I]","");[/B]
}
The problem here is that the user could still leave the prompt field blank, or click on the cancel button. If this were to happen, the browser would not notice, and allow the form to be submitted.
To cater to this, we’d need to add the return false; statement, to prevent the form from submitting, like so:
if (f.name.value.length == 0) {
f.name.value = prompt("Please enter your name.","");
[B]return false;[/B]
}
Unfortunately with the above, the form would be prevented from submitting, even if the user entered the correct information in the prompt box, which may confuse or annoy the user when nothing happens, and they have to press the submit button again.
The solution is to place another full validation block after the prompt has been shown, to check if the user filled it in as required. The code below will only shown the prompt box once, and if the user fails to fill it in as required, the standard alert box will once again appear.
if (f.name.value == 0) {
f.name.value = prompt("Please enter your name.","");
[B]if (f.name.value == 0) {
alert("Please enter your name.");
f.name.value = "";
f.name.focus();
return false;
}[/B]
}
Protecting the user from clicking the wrong button
As suggested in the HTML web forms article, many web forms no longer include a reset button, because of the concern that a user may click it by mistake and loose all their previously entered information.
If you decide that you do want to include one on your web page, you can still assist the user from this possible miss-click with a confirmation box. This type of box gives the user an OK or Cancel option, which gives them one chance to keep their currently filled in web form as it is.
The code to achieve this can be added directly to the
element, like so:
<input type="reset" name="reset" value="clear form"
[B]onclick="return confirm('[I]Are you sure you want to clear this form?[/I]');"[/B]>
If the user clicked the reset button, they will be asked to click OK to clear the form, or Cancel to leave the form data alone. Again, you may want to change the text to something more suitable to your own web site.
What about AJAX?
AJAX can be use alongside an HTML web form and JavaScript validation, but isn’t quite so easy to make use of. It’ll also require a lot of planning and testing.
Probably the most common use of AJAX on an HTML web form is to check whether or not a desired username is already registered to another account holder, allowing the individual to be told instantly that the username they wish to use is already taken, rather than continually submitting the web form.
An article or two may pop-up in future, but for the time being, AJAX is beyond the scope of this little article.
Over to you!
And there you have it. You can have a look at a very basic example form to see the above implemented online. Hopefully you’ll be able to go away and add a little bit of basic validation to your web site’s HTML form fields, and prevent too many users from sending in data that isn’t quite what you had hoped for.
If you have any questions or are in need of a little help with your HTML web form validation, you are always welcome to post as such on the Freeola web forums.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
As always, any comments, questions, and especially corrections are welcome.
You have won the Gameday prize for this post:
27/01/07 cjh Technical Post Please claim!
Also just noticed another win for you to claim, (so edited this)
01/02/07 cjh Technical Post Please claim!
Woohhhoooo....... Argos here you come.
Link to Gameday prize winners
Sadly it does appear to be a solo victory for all those who highlight important Freeola service problems here first and contribute help / valid information here !!.
This in 'stark contrast' to the other winners of prizes for 'crucial' posts on other forums, such as your favourite 5 foods or what colour pants are you wearing today ..... etc !!!, which obviously is of great value to the error free and smooth running of the web servers we all use and rely upon.
Cynical me ??
Nice one Chris. Dan
Link to thesitewizard
Link to thesitewizard
It's the ..??? character rule cut in !!
Dan
I should have spotted that one, I think Dreamweaver took exception to my manual coding then wanting rollover state buttons. Clearly refusing to create the correct code.
It clearly rebelled !!! Works OK now. Thanks
I tend to use Java validation for clients website contact forms with a basic form to mail .php to process, as Chris pointed out it's a good immediate way to make people fill in the correct required fields.
However I now use a .php to validate as I have many more fields I need to account for in the Request E mail that's generated, my Javascripting is not 'too hot' and have self taught myself to do a .php for info delivered and required fields. So all work is in the .php rescript which I can do ok.
If anyone wants to get a start with using a .php script to validate website forms into e mails, (as chris has given you the form recipe above), learn how to modify it. By looking at what is already there, adding to it and taking away req'd info if using a Javascript to validate.
I got my basic first one generated at:
Link to thesitewizard
I edit mine with DW MX and don't think frontpage can cope with php !!! not sure.
It's good as Freeola allow .php usage free. Put the .php file in your cgi-shl BUT upload it as ASCII - NOT binary, call it to process from the Contact form script as:
> I have put two pages up for you to see the validation / MX
> scripting.
>
> This page has just the rollover buttons which work fine on:
> Link to
> page
>
> This is my test contact form with Javascript validation causing
> the rollover not to work. Form works fine without rollovers on
> same page. In IE:6, I use, it has the error symbol in browser
> bar.
>
> Link to not
> working rollover contact form
>
> As a fix I now use a .php to validate, but also use one
> Javascript to prevent spam. This does not prevent rollovers
> working:
> Link to working contact
> form
>
> Thanks Dan
The broken version fails because it doesn't contain the necessary javascript. You need to paste the 'MM_swapImgRestore' code that the rollovers are trying to call.
Compare a working and broken page to see the difference. I guess you're relying on Dreamweaver to create the code and it's getting confused.
NB. You need to remove the trailing / to make your example pages display.
sorry, Dan
> Thanks Dan,
>
> Not sure about the Dreamweaver MX issue, do you have an example
> online that I can look at? There shouldn't be any clashes as
> such, although it might be that the rollover and form validation
> code may be using some of the same variables.
>
> As for the site address, I'm not to sure what you're referring
> to. http:// and www are seperate parts of a web
> address, so isn't really an either / or situation.
> http:// refers to the protocol and is required when
> making an HTML hyperlink, while www is generally the
> default sub-domain address that web site addresses us, but isn't
> really needed.
I never realised until now that you could leave out the www. in front of the domain / page name as you did in the hyperlink to the form.
I have put two pages up for you to see the validation / MX scripting.
This page has just the rollover buttons which work fine on: Link to page
This is my test contact form with Javascript validation causing the rollover not to work. Form works fine without rollovers on same page. In IE:6, I use, it has the error symbol in browser bar.
Link to not working rollover contact form
As a fix I now use a .php to validate, but also use one Javascript to prevent spam. This does not prevent rollovers working:
Link to working contact form
Thanks Dan
Not sure about the Dreamweaver MX issue, do you have an example online that I can look at? There shouldn't be any clashes as such, although it might be that the rollover and form validation code may be using some of the same variables.
As for the site address, I'm not to sure what you're referring to. http:// and www are seperate parts of a web address, so isn't really an either / or situation. http:// refers to the protocol and is required when making an HTML hyperlink, while www is generally the default sub-domain address that web site addresses us, but isn't really needed.