Javascript improvement form

Source: Internet
Author: User
Tags valid email address

Yesterday I read the chapter in "Pro JavaScript techniques" that uses js to improve the form.CodeI tried it again and debugged it with firebug for half a day. I found some small problems in the book. I will discuss them in the following review process. You are welcome to leave a message for discussion :)

In terms of forms, to verify whether the user input is valid is a duplicate, I will simply show the example in the book, first give the semantic XHTML

 

<Body> <form action = "" method = "Post"> <fieldset class = "login"> <legend> login information </legend> <label for = "username" Class = "hover"> username </label> <input type = "text" id = "username" class = "required text"/> <br/> <label for = "Password "Class =" hover "> password </label> <input type =" password "id =" password "class =" required text "/> </fieldset> <legend> Personal Information </legend> <label for = "name"> name </Label> <input type = "text" id = "name" class = "required text"/> <br/> <label for = "email"> email </label> <input type = "text" id = "email" class = "required email text"/> <br/> <label for = "date"> date </label> <Input type = "text" id = "date" class = "required date text"/> <br/> <label for = "url"> website </label> <input type = "text" id = "url" class = "url text" value = "http: // "/> <br/> <label for =" phone "> phone </label> <input type =" Text "Id =" phone "class =" phone text "/> <br/> <label for =" Age "> over 13? </Label> <input type = "checkbox" id = "Age" name = "Age" value = "yes"/> <br/> <input type = "Submit" Value = "Submit Form" class = "Submit"/> </fieldset> </form> </body>

In the form, all <input> elements are precisely divided into classes (for example, the class of an element whose type is text is also text, the required class is required, which is used as a hook for JS applications) and is included in the appropriate fieldset together with the correct label. With CSS to make it more beautiful:

 
<Style type = "text/CSS"> FORM {font-family: Arial; font-size: 14px; width: 300px;} fieldset {border: 1px solid # CCC; margin-bottom: 10px;} fieldset. login input {width: 125px;} legend {font-weight: bold; font-size: 1.1em;} label {display: block; width: 60px; text-align: right; float: Left; padding-Right: 10px; margin: 5px 0px;} input {margin: 5px 0;} input. text {padding: 0 0 0 3px; width: 172px;} input. submit {margin: 15px 0 0 70px;} </style>

I hope that the park friends who are interested in JS and learn about it will be able to knock on the Code and try it out.

The results are as follows:

After the style prototype is given, the author writes some validation functions for guidance and introduces the usage of Regular Expression matching. We skip these steps and go to the focus. First, let's look at the set of JS verification rules. We can note that all tests require common names and Semantic Error messages. The following is a set of verification rules used in this example:

VaR errmsg = {required: {MSG: 'This field is required. ', test: function (OBJ) {return trim (obj. value ). length> 0 | trim (obj. value )! = Obj. defaultvalue ;}, Email: {MSG: 'Not a valid email address. ', test: function (OBJ) {return trim (obj. value ). length <= 0 |/^ [a-z0-9 _ +. -] + \ @ ([a-z0-9-] + \.) + [a-z0-9] {2, 4} $/I. test (obj. value) ;}}, Phone: {MSG: 'Not a valid phone number. ', test: function (OBJ) {var M =/(\ D {3 }). * (\ D {3 }). * (\ D {4 })/. exec (obj. value); If (m) obj. value = "(" + M [1] + ")" + M [2] + "-" + M [3]; return trim (obj. value ). length <= 0 | M ;}, Date: {MSG: 'Not a valid date. ', test: function (OBJ) {return trim (obj. value ). length <= 0 |/^ \ D {2} \/\ D {2} \/\ D {2, 4} $ /. test (obj. value) ;}}, URL: {MSG: 'Not a valid URL. ', test: function (OBJ) {return trim (obj. value ). length <= 0 | obj. value = 'HTTP: // '|/^ HTTPS?: \ // ([A-z0-9-] + \.) + [a-z0-9] {2, 4}. * $/. Test (obj. Value );}}}

Here I have modified the verification rule. In the original article, the verification of the required item (required) is: Return obj. value. there is a problem with the length> 0 subcondition. If a series of spaces are entered and there is no substantive content, will it also pass verification? Obviously not, it is correct to use the trim function to remove spaces.

 
Function trim (value) {return value. Replace (/(^ \ s *) | (\ s * $)/g ,'');}

This function removes spaces at the beginning and end of a string by matching regular expressions using the replace method, which is very common. This problem is also true for the judgment of some other fields, such as email and date. Here we have details, such as the fields that require validation in specific formats, first, check whether the user has entered anything. If there is no such thing, there is no need to judge it. Therefore, trim (obj. value ). length <= 0 if it is true, then this | the operation ends, indicating that the user has not entered anything, so there is no need to judge the format. Otherwise, if it is false, it indicates that there is content, and you need to judge it.

The rules are given, and then we should use these rules for judgment, and then provide the necessary prompt information. Introduction: All <form> elements (in Dom) have an attribute called elements, which is an array containing all fields of the form, with this array, you can easily traverse all possible fields and check for errors. In the debugging process, we found that not only the <input> elements related to user input are in elements, but also two <fieldset> elements... the following describes the verification functions.

// Verify the function of all fields in the form. // form is a reference function of form elements. validateform (form) {var valid = true; // traverses all field elements in the form. // form. elements is an array of all fields in the form. For (VAR I = 0; I <form. elements. length; I ++) {// hide any error information first to prevent the display of hideerrors (from. elements [I]); // check whether the field contains the correct content. // Note: An inverse operator is added to the condition in the original book '! ', Read the following validatefield and you will know that there is a problem here if (validatefield (form. elements [I]) Valid = false;} return valid;} // verify the content of a single field function validatefield (ELEM) {var errors = []; // traverse all possible verification techniques for (VAR name in errmsg) {// check whether the specified class var Re = new Regexp ('(^ | \ s)' + name + '(\ s | $) has an error type in the field) '); // check whether the element carries the class and pass it to the verification function if (Re. test (ELEM. classname )&&! Errmsg [name]. test (ELEM) // If the verification fails, add the error information to the list of errors. push (errmsg [name]. MSG);} // if an error message exists, if (errors. length) showerrors (ELEM, errors); return errors. length> 0; //> 0 indicates an error message}/* displays and hides the error message of the corresponding field * // hides any misposition information currently displayed. Function hideerrors (ELEM) {// obtain the next element of the current field var next = ELEM. nextsibling; // if the next element is UL and the class is errors if (next & next. nodename = 'ul '& next. classname = 'errors ') // delete it (this is the meaning of 'hiding) ELEM. parentnode. removechild (next);} // display the error information of specific fields in the form. Function showerrors (ELEM, errors) {// obtain the next element var next = ELEM of the current field. nextsibling; // if this field is not the container we specified that contains the error if (next & (next. nodename! = 'Ul '| next. classname! = 'Errors ') {// We need to generate a next = document. createelement ('ul '); next. classname = 'errors '; // insert it to the appropriate place in the DOM // from the HTML, Here ELEM. nextsibling points to '<br/>', // while <ul>'s default display is block ELEM. parentnode. insertbefore (next, ELEM. nextsibling);} // now there is a container reference that contains errors. We can traverse all the error messages for (VAR I = 0; I <errors. length; I ++) {var li = document. createelement ('lil'); Li. innerhtml = errors [I]; // and insert it into the Dom. Next. appendchild (LI );}}

In the CSS style with the error message:

 
Ul. Errors {list-style: none; Background: # ffcece; padding: 3px; margin: 3px 0 3px 70px; font-size: 0.9em; width: 165px ;}

Let's take a look at the demo:

Not very pretty, but it's pretty good... next we will start verification. The author will discuss the verification time, for example, uniform verification during submission or individual verification for each element. I will first give the author's code:

/* Self-written event auxiliary function */function addevent (OBJ, event, eventhandler) {If (obj. addeventlistener) {obj. addeventlistener (event, eventhandler, false);} else if (obj. attachevent) {obj. attachevent (event, eventhandler) ;}}/* front Article Stopdefault function */function stopdefault (e) {If (E & E. preventdefault) E. preventdefault (); else window. event. returnvalue = false; return false;}/*** perform verification when submitting a form * // run the function watchform (form) of form verification when submitting a form) {// listen to the form submission event addevent (Form, 'submit ', function () {return validateform (form) ;});} addevent (window, 'load ', function () {var form = document. getelementsbytagname ('form') [0]; watchform (form) ;});/*** verify when the field is changed */function watchfields (form) {// traverse all fields in the form for (VAR I = 0; I <form. elements. length; I ++) {// and bind the 'change' event processing function (which listens to the defocusing of input elements) addevent (form. elements [I], 'change', function () {// re-verify this field return validatefield (this) ;}} addevent (window, 'load', function () {var form = document. getelementsbytagname ('form') [0]; // listen to all field changes in the form watchfields (form );});

at first, I tested the code in the book and found some problems. For example, if I use 'change' to listen, I first asked for an input. required gets the focus, and then I let it lose the focus, so there is no real-time feedback, because the content in the input is not changed, there is another problem, if I lose the wrong email, it will provide an error message. If I enter the error again, it will provide two duplicate error messages... even more seriously, even if an error occurs, the 'submit 'binding function returns "false" or "Submit". I am also confused here. Later I used the stopdefault function above, I think the desired results should be combined with the real-time verification of a single input element and the overall verification of Form submission. The modified code is shown below:

/* Modified watchfields */function watchfields (form) {for (VAR I = 0; I <form. elements. length; I ++) {addevent (form. elements [I], 'blur', function () {// first remove the original error information to prevent repeated error messages hideerrors (this ); // Add By Myself return validatefield (this) ;}}/* modified watchform */function watchform (form) {addevent (Form, 'submit ', function (e) {// If the verification fails, the event if (! Validateform (form) stopdefault (e) ;});} addevent (window, 'load', function () {var form = document. getelementsbytagname ('form') [0]; // listens to The Blur event watchfields (form) of each input element; // listens to the form submission event watchform (form );});

OK. The problem is solved here and the complete instance is downloaded. If you have any questions, please discuss them :)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.