Create reusable and scalable JavaScript verification form scripts

Source: Internet
Author: User

If you need to collect information from the user, you need to use the form.

A form contains most common graphic interface elements, such as text boxes, single-choice buttons, check boxes, and drop-down menus.

After entering the form, click the submit button to send the form to the Web server. Although the verification can be completed through the CGI program on the server, it is much faster to use JavaScript For verification on the client, in addition, user operations are highly efficient.


This blog mainly shares with you an extensible Javascript script (version 1.0) that I wrote to verify the reusability of forms.

Let's take a look at the implementation results:

1. Initial form


2. Submit,

If the email is empty, then:


3. If the email does not comply with the rules:


4. If no drop-down box is selected:


5. If one of the radio buttons is not selected:


6. other fields are automatically selected based on the selected fields: Select normaluser to automatically select 2G

Verify that at least one of the two is selected: If no address is entered or the address is not selected, then:


7. Verification zip code: If the entered incorrect zip code is:


8. verification file: If the incorrect image format is entered:


Javascript script (validform1.js ):

// JavaScript documentwindow. onload = initforms; function initforms () {for (VAR I = 0; I <document. forms. length; I ++) {// traverse all forms and perform the verification document. forms [I]. onsubmit = function () {return validform () ;}}; // the check box normaluser registers the event document. getelementbyid ("normaluser "). onclick = spaceset;}; function validform () {var Allgood = true; // obtain all tags var alltags = document. getelementsbytagname ("*"); For (VAR I = 0; I <alltags. length; I ++) {// check all labels if (! Validtag (alltags [I]) {Allgood = false ;};}; return Allgood; // checks whether the tag is valid. Function validtag (thistag) {var outclass = ""; // obtain the class attribute var allclasses = thistag of the label. classname. split (""); For (var j = 0; j <allclasses. length; j ++) {// verify the tag, and change the invalid tag outclass + = validbasedonclass (allclasses [J]) + "" ;}; thistag. classname = outclass; If (outclass. indexof ("invalid")>-1) {// identifies the label invalidlabel (thistag. parentnode); // The tag is invalid. Thistag. focus (); // If the tag is input, select the text if (thistag. nodename = "input") {thistag. select () ;}; return false ;}; return true; // identifies an invalid field. Add the class name invalidfunction validbasedonclass (thisclass) {var classback = ""; // verify, here, we can extend the verification switch (thisclass) {Case ": Case" invalid ": break; Case" reqd ": // judge if (Allgood & thistag. value = "") // there is a space after invalid {classback = "invalid" ;}; classback + = thisclass; break; Case "radio ": // check whether the selected distinct if (allg Ood &&! Radiopicked (thistag. Name) {classback = "invalid" ;}; classback + = thisclass; break; Case "isnum": // check whether it is a number if (Allgood &&! Isnum (thistag. Value) {classback = "invalid" ;}; classback + = thisclass; break; Case "isemail": // check whether it is emailif (Allgood &&! Isemail (thistag. value) {classback = "invalid" ;}; classback ++ = thisclass; break; Case "isimage": // check whether it is an image, it can be evolved to check the file name if (Allgood &&! Isimg (thistag. Value) {classback = "invalid" ;}; classback + = thisclass; break; Case "ispostcode": // check the zip code if (Allgood &&! Ispostcode (thistag. value) {classback = "invalid" ;}; classback ++ = thisclass; break; Case "isaddress": classback + = thisclass; break; default: // there is a space after invalid // check whether at least one of the two fields has been set if (Allgood &&! Crosscheck (thistag, thisclass) {classback = "invalid" ;}; classback ++ = thisclass ;}; return classback ;}; // check whether at least one of the two fields has been set // This is the function crosscheck (intag, otherfieldid) prepared for the zip code field and address list element {If (! Document. getelementbyid (otherfieldid) {return false ;}; return (intag. value! = "" | Document. getelementbyid (otherfieldid). value! = "")}; // Tag function invalidlabel (parenttag) {If (parenttag. nodename = "label") {// there is a space parenttag before invalid. classname + = "invalid" ;};}; // make sure that you have selected a single-choice Button Function radiopicked (radioname) {var radioset = ""; // loop traversal form, if you find the single-choice button group, radio will contain a value for (var k = 0; k <document. forms. length; k ++) {// set radioset to the name of the radio button group in the form being viewed if (! Radioset) {radioset = Document. Forms [k] [radioname] ;};}; // if the single-choice button group cannot be found, false is returned. If (! Radioset) {return false;} // check each single-choice button. If one is selected, truefor (k = 0; k <radioset. length; k ++) {If (radioset [K]. checked) {return true ;};}; // if no selected single button is found, false return false;} is returned; // check whether it is a digital function isnum (passedval) {// if the field is empty, it is definitely not an array. If (passedval = "") {return false ;}for (var k = 0; k <passedval. length; k ++) {// charat function returns the character at the position K of the field and checks whether it is a number if (passedval. charat (k) <"0") {return false;} If (passedval. charat (k)> "9") {RET Urn false ;}; return true}; // check the email address in pure JavaScript (without a regular expression). It only checks that the entered content conforms to the correct form of email and cannot confirm whether it exists. Function validemail (email) {// verify whether there are spaces, slashes, colons, semicolons, and other invalid characters var invalidchars = "/:,;"; if (email = "") {return false ;}; for (var k = 0; k <invalidchars. length; k ++) {var badchar = invalidchars. charat (k); If (email. indexof (badchar)>-1) {return false ;};}; // verify whether @ var atpos = Email exists. indexof ("@", 1); If (atpos =-1) {return false ;}; // verify that @ already exists if (email. indexof ("@", atpos + 1 )! =-1) {return false ;}; // verify whether a vertex var periodpos = Email exists. indexof (". ", atpos); If (periodpos =-1) {return false ;}; // check whether there are at least two characters after the point number if (periodpos + 3> email. length) {return false ;}; return true ;}; // use a regular expression to check the email address (recommended) function isemail (email) {var reemail =/^ \ W + ([\. -]? \ W +) * @ \ W + ([\.-]? \ W + )*(\. \ W {2, 3}) + $/; return reemail. test (email) ;}; // use a regular expression to check whether the file suffix is GIF or jpgfunction isimg (newurl) {var reimg =/^ (File | HTTP ): \/\ s + \. (GIF | JPG) $/I; return reimg. test (newurl) ;}; // verify the zip code function ispostcode (postcode) {var repostcode =/^ [0-9] {6 }$/; return repostcode. test (postcode) ;}/// you can extend the verification content here, for example, // verify the landline number // verify the mobile phone number };}; // automatically set the field input function spaceset () {If (this. checked) {document. getelementbyid ("space2 "). checked = true;} else {document. getelementbyid ("space2 "). checked = false ;};};

Note: I try to write it in detail. You should be able to understand it.

Reusable:

It basically covers the verification methods of the most common controls on forms.

Scalable, method:

In this location

Add the class attribute of the tag you want to verify,

 Then,


Add your verification method.


HTML document:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

Csssample table (validform.css ):

@ Charset "UTF-8";/* CSS document */body {color: #000; Background-color: # FFF;} input. invalid {/* When the input is invalid, use this style */background-color: # ff9; Border: 2px red inset;} label. invalid {/* use this style when the input is invalid */color: # f00 ;}

Welcome!

The improvements will be put into version 2.0!

Related Article

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.