Home > JavaScript >
HTML Forms Validation on the Client Side | Sitemap Search |
|
Sections Membership Features
Recent comments
very difficult by alfin Taking the credit for another persons work ? by curious dude. |
HTML Forms Validation on the Client SidePosted by martin on 16 Sep 2002, last updated on 28 Sep 2002. Form validation on the client-side is essential - it saves time and bandwidth; you also have better control to show the user the wrong field. This comparison of different validation methods includes comments for improving portability and maintainability. Why is Client Side Validation Good
Two Major Validation Approaches
While displaying all errors is needed in case of server validation, the better method for client validation is to show one error at a time. This makes it possible to highlight the wrong field, making it a lot easier for the visitor. If you print all errors most people would also try to remember and correct them at once instead of trying to submit after each correction. Considering these advantages I will focus only on validation methods that display one error at a time. How to Validate FormsTake for example the following code fragment:
<script type="text/javascript" language="javascript">
function validateMyForm() {
if (parseInt(document.forms[0].phone.value) !=
document.forms[0].phone.value) {
alert('Please enter a phone number, numbers only');
return false;
}
return true;
}
</script>
<form action="handler" onsubmit="return validateMyForm();">
<p>Phone: <input type="text" id="phone" name="phone" /></p>
<p><input type="submit" value="Send" /></p>
</form>
So what's wrong: If you add another form before this one the code will try to validate the wrong one. Note: JavaScript is case sensitive, the value which is assigned to the HTML id/name attribute is also case sensitive. A better approach would be to add a form name:
function validateMyForm() {
if (parseInt(document.forms.myForm.phone.value) !=
document.forms.myForm.phone.value) {
<form id="myForm" name="myForm" action="handler"
onsubmit="return validateMyForm();">
This is definitely better but still not portable enough - if you want to reuse some of the validation for another form you will have to do a lot of text replacing. Let's remove the form name:
function validateMyForm(form) {
if (parseInt(form.phone.value) != form.phone.value) {
<form action="handler"
onsubmit="return validateMyForm(this);">
The last method makes use of the Now how about making visitors' lives a lot easier and focus the field that triggered the error instead of making them find it on their own.
function validateMyForm(form) {
if (parseInt(form.phone.value) != form.phone.value) {
alert('Please enter a phone number, numbers only');
form.phone.focus();
form.phone.select();
return false;
}
With these changes the browser will focus the wrong field and even select the text for the visitor, if scrolling is needed it will also happen automatically. That was pretty good, but don't you feel that it's a little too much code for every single field? If we create a simple library of functions we can save lots of typing and download time for the page. Well next we'll do exactly this and define our basic functions that make validation code even shorter.
function validateNumber(field, msg, min, max) {
if (!min) { min = 0 }
if (!max) { max = 255 }
if ( (parseInt(field.value) != field.value) ||
field.value.length < min ||
field.value.length > max) {
alert(msg);
field.focus();
field.select();
return false;
}
return true;
}
This function does a simple validation of a number - it checks whether the field contains digits only, and optionally if it is within a given range. We are passing the error message as a parameter to it, to use such a function we can basicly add it to the onsubmit handler like:
<form action="handler"
onsubmit="return validateNumber(this.phone,
'Please enter a phone number, digits only', 5, 10);">
So called it will check if the phone is numeric, it is more than 5 digits and less than 10. Note how the phone object is passed as a parameter, this allows us to focus it via the helper function as opposed to passing the value of the field only. Another method for validating numbers is to require them to be in a given range, to make the function do this kind of checks simply change the check line to:
if ((parseInt(field.value) != field.value) ||
field.value < min ||
field.value > max) {
If you want to apply more than one checks to the form you can embed several rules in the onsubmit handler, imagine that we also require first and last name to be entered:
<form action="handler"
onsubmit="return (
validateNumber(this.phone,
'Please enter a phone number, numbers only', 5, 10) &&
validateString(this.firstName,
'Please enter your first name', 3, 15) &&
validateString(this.lastName,
'Please enter your last name', 3, 15)
);">
The code requires all validation rules to evaluate to true (with the logical AND - &&). A closer look reveals the fact that it is very easy to generate such code from a server scripting language, but that's a whole another article.
function validateString(field, msg, min, max) {
if (!min) { min = 1 }
if (!max) { max = 65535 }
if (!field.value || field.value.length < min || field.value.max > max) {
alert(msg);
field.focus();
field.select();
return false;
}
return true;
}
As you can see the string validation function looks more or less the same; you can also write other functions and combine them with these too. A common field required in many forms on the web is the email, there're lots of functions I've seen but usually the simplest and easiest way to validate an email is using regular expressions. We'll extend the function, making it possible to define the field as optional.
function validateEmail(email, msg, optional) {
if (!email.value && optional) {
return true;
}
var re_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+$/;
if (!re_mail.test(email.value)) {
alert(msg);
email.focus();
email.select();
return false;
}
return true;
}
To validate a required email you should call it as validateEmail(this.email, 'Please enter your email address') and if you want it to be optional: validateEmail(this.email, 'Please enter a correct email address or leave the field blank', true). JavaScript cannot be used on its own for validation, but it helps a lot if you have it. The more compact code you embed in your HTML, the better - it saves download time and search engines will like you. Commentsonsubmit script by Chris (chris@usbox.com) on 3 Dec 2002 3:00pm GMT I'm looking for a way to validate a input text field named "quantity". i want script to see if the number intered is divisable by another number (like 100 for example) and if the answer is a whole number then submit... otherwise show alert text "your Quantity is not correct" Is that possible and if so would you tell me how or send me somewhere to show me Thanks Chris modulus by mark (mark_dw@spam_me_and_die_hotmail.com) on 11 Dec 2002 7:51pm GMT you should be able to use modulus for that...if javascript supports it, it would go somethin like this.... if (quantity%100==0) { do stuff here } it works in PHP....never tried it in javascript, but modulus is a pretty basic math function. Modulus (%) returns the remainder...above it would divide quantity by 100 and returns the remainder...so if quantity was 105, it would return 5. if they put in a multiple of 100, it would return 0. Form validation by Paul Harrison (maulermorg1979@hotmail.com) on 22 Feb 2003 7:50pm GMT Desperately trying to work out how to validate a form, in the top half of a frame with JavaScript, on clicking the submit button, and then getting the validated data to appear in the bottom half of the frame. Any help would be great. Thanks Comments by Grant Prellwitz () on 16 Apr 2003 9:40pm GMT A few comments: 1) While I allow that there are definite advantages to highlighting the invalid field, it's more user-friendly to show them as many of their problems as possible. The best wat would be to flag all the invalid fields with a graphic or by changing the class in the DOM. 2) Yes, JavaScript supports modulo using the percent sign (%). 3) Since all top level domains have at least two characters, your e-mail validation could reflect that: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]){2,}$ Whole number by Sohel () on 18 Apr 2003 8:09pm GMT Javascript does not support code or modulo(%) i.e if (quantity%100==0){} . It returns the same number as what quantity contains. good by urmila (hiurmi@yahoo.co.in) on 23 Apr 2003 12:30pm GMT I m happy with this site Validate text box using on_blur by Brent Gouge (brent910@tpg.com.au) on 23 May 2003 2:13am GMT Hi there I want to be able to validate an input text box field (name = 'First Name') using the on_blur event handler in JavaScript. It needs to loop throught the string given in the field to determine that all characters entered are alpha characters only. Any help would be appreciated Re: Validate text box using on_blur by martin on 24 May 2003 7:08pm GMT The best way to do that I'm aware of is using < href="http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/index.html">regular expressions. Thank You by hepa () on 15 Jun 2003 2:16pm GMT Your tutorial is so far the best I was able to find on the web. Great Job! Thanx for such a great service. I think that there might be a small error under function validateString if (!field.value || field.value.length < min || field.value.max > max) should it not be {if (!field.value || field.value.length < min || field.value.length > max) { comments by joanna (crisparsoo@yahoo.com) on 18 Jun 2003 1:49pm GMT there is a lack of srtuctured codes.A beginner will have difficulties in understanding what has been explained. Validation Problem by yacoob (yacoob.sadiq@smartstream-md.com) on 23 Jun 2003 10:07am GMT If a name of the textfield is having space its not allowing me to validate for eg if firstName is writern like First Name validateString(this.First Name, 'Please enter your first name', 3, 15) Can you please help me with this thank you yacoob validating First, middle and last name by roland james (fare006@yahoo.com) on 4 Aug 2003 1:43am GMT how can i check if the input in first name or last name or middle is a combination of numbers and special characters so that if the client input in it alerts "soory invalid entry" thank you Great JOB dude by Dhanraj sheth (maildhanraj@yahoo.co.in) on 7 Aug 2003 8:25pm GMT thanks a lot u have donw a GREAT job by this tutorial Good stuff by () on 1 Sep 2003 8:48am GMT Good stuff, specially for begginners! Form Validation by cityslicker on 5 Nov 2003 11:52pm GMT I would like to ensure that a CheckBox is checked before submitting the form. The trouble is, the form has webbots (!), anyone can suggest a solution. Here's what I do: <form name= "RespForm" method="POST" action="--WEBBOT-SELF--" onSubmit="location.href='_derived/nortbots.htm';return false;" webbot-onSubmit> <!--webbot bot="SaveResults" u-file="_private/feedback.txt" s-format="HTML/BR" s-label-fields="TRUE" b-reverse-chronology="FALSE" s-email-format="HTML/BR" b-email-label-fields="TRUE" b-email-subject-from-field="FALSE" s-email-subject="Customer Feedback" s-builtin-fields s-email-address="CitySlickerz@aol.com" startspan --><strong>[FrontPage Save Results Component]</strong><!--webbot bot="SaveResults" endspan i-checksum="6561" --> .. .. .. Here's the Checkbox: <input type="checkbox" name="C1" value="OFF"> Please confirm <span lang="en-gb">your acceptance of above Terms and Conditions</span></dd> <dt> </dt> <p><input type="submit" value="Submit" onClick="funtest()"> <input type="reset" value="Clear Form"></p>
</form> .. and here's the validation .. <script language="JavaScript"> function funtest() { if (!(document.RespForm.C1.checked)) { alert ('Please check the box') return false } } </script> The trouble is, even though JavaScript reports the error, the form is still submitted. How can I stop it from being sent to the Server? Many thanks Alex Form validation server side by Bill Nedell (bill@wynde.com) on 28 Nov 2003 11:29pm GMT What does one do if they need to intercept a submit but do checking on the server side. I want to create a form for file upload but I want to check the file name against a server side database before letting the submit continue to the browser upload code. It seems like being able to call PHP code from onSubmit would be the trick but from I've read and tried you can't call PHP from onsubmit. Script by luciano (luciano@infoconceptlc.com) on 13 Feb 2004 10:18pm GMT I would like to check the validity of an e-mail address on a form before the form is sent to me.
I would like a validation function to check anybody users has entered a valid email address in a form. Exceution of java script by vaibhav arya (arya_vaibhav@rediffmail.com) on 14 Feb 2004 4:44am GMT IN HTMl form java script is define in Head, body and HTML tag. What is the difference between them Compare 2 email addreses by Croydon (croydon@xtra.co.nz) on 25 Feb 2004 12:23pm GMT In a form to email booking form I need to compare "emter email address" and "please reenter email address" to see if they are the same. We are getting many incorrect email addtrsses from "typo's". The scripts I have tried are working in the demo sites but not on my page. Is this because the other forms on the page interferring. The form I wish to check is at: www..gisbornecolonial.co.nz/form.html Thanks Croydon long running validation by Rob (casro14@ca.com) on 26 Feb 2004 4:36am GMT In the onsubmit handler, if the validation checks take a long time (lots and lots of calculations), and I want to display a wait page before validating, how can I do this. I tried to modify the current display before calling validation, but it didn't work. The display changed only after returning from the onsubmit handler. help... by Aks (ada_khan@yahoo.com) on 11 Mar 2004 6:28pm GMT i want to get the text from the combo box into the text filed simply on loosing focus from the combo... how it is possible... ??? simple input validation by Richie (niyioyelade@yahoo.com) on 17 Mar 2004 2:20pm GMT do // input cost of single item { con.out.println("Enter the cost of item "+countitemtype); costsingle=con.input.readDouble(); if (costsingle<=0.00) con.out.println("Invalid entry! Please try again"); } while (costsingle<=0.00 || (costsingle>='a' && costsingle<='z')); How do I ensure a wrong input of a number instead of a letter does not stop my program from running? e-mail vlaidation by gaurav (chandnagaurav@rediffmail.com) on 19 Mar 2004 7:50am GMT how to validate email id field when we r making it through applet onSubmit then page by Duncan (drack@mweb.co.zw) on 12 Apr 2004 9:58am GMT on invoking the onSubmit handler i want the from to be validated and if its OK to be mailed to me ,then a thank you pag be displayed '' I would appreciate your help so much regarding form validation by jsnrao (jsatya@linux.net) on 21 Jun 2004 6:42am GMT see in this u have described only for numeric data validation, but if i need to perform some varchar2,date format validation iam getting problem. But it is a very useful book. regarding form validation by jsnrao (jsatya@linux.net) on 21 Jun 2004 6:43am GMT see in this u have described only for numeric data validation, but if i need to perform some varchar2,date format validation iam getting problem. But it is a very useful book. java script by prab kar (php@rediffmail.com) on 1 Jul 2004 4:29am GMT hello i have a validation function which prevents the users from entering spl chars, allows to enter only alpha-numerics, but i want to make it allow to enter space between the name ex: "Prab test" my check str is:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; http://www.evolt.org/article/Regular_Expressions_i by () on 11 Aug 2004 7:51pm GMT http://www.evolt.org/article/Regular_Expressions_in_JavaScript/17/36435/index.html Sorry by () on 11 Aug 2004 7:52pm GMT I didn't mean to put that site there, my bad! I didn't realize the focus wasn't in the address bar!!! Two text box validation by Anu (anilachopin@hotmail.com) on 13 Sep 2004 3:45pm GMT I need to validate the second text box based on the value that the user entered in the first text box. ie..the difference between the value that entered in the first text and the second text box should not be greater than 13. Please help me Check for Y or N by pat () on 28 Oct 2004 1:21am GMT I would like to know how to do a field validation ie check for a Y or N, throw an alert if it is other then a Y or N if (document.FrontPage_Form1.PS.value != "N" ) { window.alert('Please enter either a Y or N as in the is thistext field'); return false; } trial by abc () on 25 Nov 2004 5:26am GMT wanted to check how can a form be validated & the action to be taken is submitting it through mail using mailto on clicking submit button Help needed. by Masil (masil@saitran.com) on 29 Nov 2004 10:48pm GMT The validation doesn't work on my side can someone help? <script type="text/javascript" language="javascript"> function validateNumber(field, msg, min, max) { if (!min) { min = 0 } if (!max) { max = 255 } if ( (parseInt(field.value) != field.value) || field.value.length < min || field.value.length > max) { alert(msg); field.focus(); field.select(); return false; } return true; } function validateString(field, msg, min, max) { if (!min) { min = 1 } if (!max) { max = 65535 } if (!field.value || field.value.length < min || field.value.max > max) { alert(msg); field.focus(); field.select(); return false; } return true; } function validateEmail(email, msg, optional) { if (!email.value && optional) { return true; } var re_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+$/; if (!re_mail.test(email.value)) { alert(msg); email.focus(); email.select(); return false; } return true; } </script> [...] <FORM method="POST" action="" onSubmit="return uSubmit(this) && validateNumber(this.WPHONE, 'Please enter a valid phone number, numbers only', 5, 10) && validateString(this.INITIAL, 'Please enter only one character', 0, 1) && validateEmail(this.EMAIL, 'Please enter a correct email address or leave the field blank', true) "> response to alex by ahmed () on 1 Dec 2004 8:34pm GMT if you have an onclick on a submit button, the page is going to be submitted regarless. instead make it just a button instead of a submit button and perform the submit action in your function. Date Validation in Combo Boxes by Sajid Mushtaq (sajidmraj@hotmail.com) on 20 Dec 2004 1:06pm GMT Please send me the Date validation Combo Box. This should be like that if I select month, the days related to this field should be displayed on another combo. The years should also be in another combo box. test\"test by test if this is work () on 28 Dec 2004 10:03pm GMT I want validate test\"test any validation for not allowing HTML tags. by Nick () on 6 Jan 2005 5:53am GMT <html> <head> </head> <script language="javascript"> document.location.href="xyz.html"; </script> <body> I dont want to allow such JS and HTML codes to input in my one form. How can i do this? </body> </html> Waiting for reply. Nick. nice site by Nik (nik@excite.com) on 10 Jan 2005 12:14am GMT Your site is really nice. Got lots of information. thanks Nothing by ujwal () on 12 Jan 2005 4:44pm GMT Thanks for u input focus by sushil (sushil.poddar@caritor.com) on 21 Jan 2005 1:28pm GMT Is there any way to check using JavaScript whether the focus is available in any one of the given set of input tags? Please reply quickly, if possible with code average by rajeev (rover_rajeev@yahoo.co.in) on 25 Jan 2005 7:33am GMT Its good but u would have provided info on validating forms with respect to dates... KeyPress by ulev (ulev@rediffmail.com) on 28 Jan 2005 5:14am GMT Good!Is there anyway to check the data when it is entered and alert it there itself?I know we have to use keypress. Can u focus an article on it. Thanks. |