19468373 Javascript Form Validation

download 19468373 Javascript Form Validation

of 18

Transcript of 19468373 Javascript Form Validation

JavaScript Form Validation : quick and easy!Using client side JavaScript is an efficient way to validate the user input in web forms. When there are many fields in the form, the JavaScript validation becomes too complex. The JavaScript class presented here makes the form validations many times easier. Contents

1. Download the JavaScript form validation script

2. Using the form validation script

3. Adding a custom validation

4. Table of Validation Descriptors

5. Showing all the form validation errors together

6. Showing the form validation errors on the page itself

7. Form validation without coding!

How to add JavaScript Form Validation quicklyThe idea is to create a set of "validation descriptors" associated with each element in a form. The "validation descriptor" is nothing but a string specifying the type of validation to be performed. Each field in the form can have 0, 1, or more validations. For example, the input should not be empty, should be less than 25 chars, should be alpha-numeric, etc You can associate a set of validation descriptors for each input field in the form.

Download the JavaScript form validation scriptYou can download the JavaScript form validation script here.

The zip file contains the java script file, documentation and examples.

Using the form validation script1.Include gen_validatorv31.js in your html file just before closing the HEAD tag

2. Just after defining your form, Create a form validator object passing the name of the form varfrmvalidator=newValidator("myform"); ....

3. Now add the validations requiredfrmvalidator.addValidation("FirstName","alpha");

the first argument is the name of the field and the second argument is the validation descriptor, which specifies the type of validation to be performed. You can add any number of validations. The list of validation descriptors are provided at the end of the documentation. The optional third argument is the error string to be displayed if the validation fails.frmvalidator.addValidation("FirstName","alpha"); frmvalidator.addValidation("FirstName","req","PleaseenteryourFirstName"); frmvalidator.addValidation("FirstName","maxlen=20", "MaxlengthforFirstNameis20");

4. Similarly, add validations for the fields where validation is required. That's it! You are ready to go.

ExampleThe example below will make the idea clearer First Name Last Name EMail

Phone Address Country [choose yours] Albania Algeria American Samoa Andorra Angola Anguilla Antarctica Antigua And Barbuda Argentina Armenia Aruba

varfrmvalidator=newValidator("myform"); frmvalidator.addValidation("FirstName","req","PleaseenteryourFirstName"); frmvalidator.addValidation("FirstName","maxlen=20", "MaxlengthforFirstNameis20"); frmvalidator.addValidation("FirstName","alpha"); frmvalidator.addValidation("LastName","req"); frmvalidator.addValidation("LastName","maxlen=20"); frmvalidator.addValidation("Email","maxlen=50"); frmvalidator.addValidation("Email","req"); frmvalidator.addValidation("Email","email"); frmvalidator.addValidation("Phone","maxlen=50"); frmvalidator.addValidation("Phone","numeric"); frmvalidator.addValidation("Address","maxlen=50"); frmvalidator.addValidation("Country","dontselect=0");

Some Additional NotesThe form validators should be created only after defining the HTML form (only after the tag. ) Your form should have a distinguished name. If there are more than one form in the same page, you can add validators for each of them. The names of the forms and the validators should not clash. You can't use the javascript onsubmit event of the form if it you are using this validator script. It is because the validator script automatically overrides the onsubmit event. If you want to add a custom validation, see the section below

Adding a custom validationIf you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps: Create a javascript function which returns true or false depending on the validation.functionDoCustomValidation() { varfrm=document.forms["myform"]; if(frm.pwd1.value!=frm.pwd2.value) { sfm_show_error_msg('ThePasswordandverifiedpassworddonnotmatch!',frm.pwd1); returnfalse; } else { returntrue; } }

sfm_show_error_msg() displays the error message in your chosen style. The first parameter is the error message and the second parameter is the input object. Associate the validation function with the validator object.frmvalidator.setAddnlValidationFunction("DoCustomValidation");

The custom validation function will be called automatically after other validations. If you want to do more than one custom validations, you can do all those validations in the same function.functionDoCustomValidation() { varfrm=document.forms["myform"]; if(false==DoMyValidationOne()) { sfm_show_error_msg('ValidationOneFailed!'); returnfalse; } else if(false==DoMyValidationTwo()) { sfm_show_error_msg('ValidationTwoFailed!'); returnfalse;

} else { returntrue; } }

where DoMyValidationOne() and DoMyValidationTwo() are custom functions for validation.

Clear All ValidationsIn some dynamically programmed pages, it may be required to change the validations in the form at run time. For such cases, a function is included which clears all validations in the validator object.frmvalidator.clearAllValidations();

this function call clears all validations you set. You will not need this method in most cases.

Set focus on validation failureBy default, if there is a validation error, the focus is set on the input element having the error. You can disable this behavior by calling:frmvalidator.EnableFocusOnError(false);

Table of Validation Descriptorsrequired req maxlen=??? maxlength=??? minlen=??? minlength=??? alphanumeric / alnum The field should not be empty checks the length entered data to the maximum. For example, if the maximum size permitted is 25, give the validation descriptor as "maxlen=25" checks the length of the entered string to the required minimum. example "minlen=5" Check the data if it contains any other characters other than alphabetic or numeric characters

alphanumeric_space / Allows only alphabetic, numeric and space characters alnum_s num numeric dec decimal alpha alphabetic alpha_s alphabetic_space email Check numeric data (allow only digits) Allow numbers (with decimal point) Check alphabetic data. Check alphabetic data and allow spaces. The field is an email field and verify the validity of the data.

lt=??? lessthan=??? gt=??? greaterthan=??? regexp=???

Verify the data to be less than the value passed. Valid only for numeric fields. example: if the value should be less than 1000 give validation description as "lt=1000" Verify the data to be greater than the value passed. Valid only for numeric fields. example: if the value should be greater than 10 give validation description as "gt=10" Check with a regular expression the value should match the regular expression. example: "regexp=^[A-Za-z]{1,20}$" allow up to 20 alphabetic characters. This validation descriptor is valid only for select input items (lists) Normally, the select list boxes will have one item saying 'Select One' or some thing like that. The user should select an option other than this option. If the index of this option is 0, the validation description should be "dontselect=0" This validation descriptor is valid only for check boxes. The user should not select th given check box. Provide the value of the check box instead of ?? For example, dontselectchk=on This validation descriptor is valid only for check boxes. The user should select th given check box. Provide the value of the check box instead of ?? For example, shouldselchk=on Checks whether at least one radio button is selected.

dontselect=??

dontselectchk

shouldselchk selone_radio

VERY EDUCATIVE

javascript form validationThere's nothing more troublesome than receiving orders, guestbook entries, or other form submitted data that are incomplete in some way. You can avoid these headaches once and for all with JavaScript's amazing way to combat bad form data with a technique called "form validation".Advertise on Tizag.com

The idea behind JavaScript form validation is to provide a method to check the user entered information before they can even submit it. JavaScript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it. In this lesson we will be reviewing some basic form validation, showing you how to check for the following: If a text input is empty or not If a text input is all numbers If a text input is all letters If a text input is all alphanumeric characters (numbers & letters) If a text input has the correct number of characters in it (useful when restricting the length of a username and/or password) If a selection has been made from an HTML select input (the drop down selector) If an email address is valid

How to check all above when the user has completed filling out the form

This lesson is a little long, but knowing how to implement these form validation techniques is definitely worth the effort on your part. Remember to check out Tizag's HTML forms lesson if you need to brush up on your form knowledge.

form validation - checking for non-emptyThis has to be the most common type of form validation. You want to be sure that your visitors enter data into the HTML fields you have "required" for a valid submission. Below is the JavaScript code to perform this basic check to see if a given HTML input is empty or not.

JavaScript Code:// If the length of the element's string is 0 then display helper message function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); // set the focus to this input return false; } return true; }

The function notEmpty will check to see that the HTML input that we send it has something in it. elem is a HTML text input that we send this function. JavaScriptstrings have built in properties, one of which is the length property which returns the length of the string. The chunk of code elem.value will grab the string inside the input and by adding on length elem.value.length we can see how long the string is. As long as elem.value.length isn't 0 then it's not empty and we return true, otherwise we send an alert to the user with a helperMsg to inform them of their error and return false.

Working Example: function notEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); return false; } return true; } Required Field:

Display:

Required Field:

form validation - checking for all numbersIf someone is entering a credit card, phone number, zip code, similar information you want to be able to ensure that the input is all numbers. The quickest way to check if an input's string value is all numbers is to use a regular expression /^[0-9]+$/ that will only match if the string is all numbers and is at least one character long.

JavaScript Code:// If the element's string matches the regular expression it is all numbers function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }

What we're doing here is using JavaScript existing framework to have it do all the hard work for us. Inside each string is a function called match that you can use to see if the string matches a certain regular expression. We accessed this function like so: elem.value.match(expressionhere). We wanted to see if the input's string was all numbers so we made a regular expression to check for numbers [0-9] and stored it as numericExpression. We then used the match function with our regular expression. If it is numeric then match will return true, making our if statement pass the test and our functionisNumeric will also return true. However, if the expression fails because there is a letter or other character in our input's string then we'll display our helperMsg and return false.

Working Example: function isNumeric(elem, helperMsg){ var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } Numbers Only:

Display:

Numbers Only:

form validation - checking for all lettersThis function will be identical to isNumeric except for the change to the regular expression we use inside the match function. Instead of checking for numbers we will want to check for all letters. If we wanted to see if a string contained only letters we need to specify an expression that allows for both lowercase and uppercase letters: /^[a-zA-Z]+$/ .

JavaScript Code:// If the element's string matches the regular expression it is all letters function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }

Working Example: function isAlphabet(elem, helperMsg){ var alphaExp = /^[a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } } Letters Only:

Display:Letters Only:

form validation - checking for numbers and lettersBy combining both the isAlphabet and isNumeric functions into one we can check to see if a text input contains only letters and numbers.

JavaScript Code:

// If the element's string matches the regular expression it is numbers and letters function isAlphanumeric(elem, helperMsg){ var alphaExp = /^[0-9a-zA-Z]+$/; if(elem.value.match(alphaExp)){ return true; }else{ alert(helperMsg); elem.focus(); return false; } }

form validation - restricting the lengthBeing able to restrict the number of characters a user can enter into a field is one of the best ways to prevent bad data. For example, if you know that the zip code field should only be 5 numbers you know that 2 numbers is not sufficient. Below we have created a lengthRestriction function that takes a text field and two numbers. The first number is the minimum number of characters and the second is the maximum number of a characters the input can be. If you just want to specify an exact number then send the same number for both minimum and maximum.

JavaScript Code:function lengthRestriction(elem, min, max){ var uInput = elem.value; if(uInput.length >= min && uInput.length