Have one of your own JavaScript form validation Plug-ins _javascript tips

Source: Internet
Author: User
Tags prev tagname visibility

You have written a form verification plug-in that is simple to use and can later extend more functionality, such as AJAX validation.

There is a span tag for each form element that needs to be validated, and the class of the tag has a valid that requires validation and, if there is a nullable, is nullable; rule represents validation rules, MSG indicates error message; To represents the name value of the element to validate. If the element is single, to can not write. The plugin iterates through each of the valid span tags, finds the elements that need to be validated, and, based on rule validation, displays a red border and an error message when the mouse is over the element.

Verification Time: 1, click the Submit button to call the validation method explicitly, 2, when the element triggers blur validation.

Plug-in code:

Css:

. failvalid
{
 border:solid 2px red!important;
}

Js:

/** * Verification Plug-in */simpovalidate = {//validation rules: {int:/^[1-9]\d*$/, Number:/^[+-]?\d*\.? 
   \d+$/},//Initialize Init:function () {$ ("span[class*= ' valid ']"). each (function () {//traverse span var Validspan = $ (this);
   var to = validspan.attr ("to");
   var target;
   if (to) {target = $ ("input[name= '" + to + "'],select[name= '" + to + "'],textarea[name= '" + to + "']");
   else {var target = Validspan.prev ();
    } if (target) {Target.blur (function () {Simpovalidate.validone (target, Validspan);
   });
 }
  });

  },//Verify all, verify successful return True Valid:function () {var bl = true;
   $ ("span[class*= ' valid ']"). each (function () {//traverse span var Validspan = $ (this);
   var to = validspan.attr ("to");
   var target;
   if (to) {target = $ ("input[name= '" + to + "'],select[name= '" + to + "'],textarea[name= '" + to + "']");
   else {target = Validspan.prev (); } if (target) {if (!
    Simpovalidate.validone (target, Validspan)) {bl = false;
}
   }  });
 return BL;

  },//single validation, validation successfully returns True Validone:function (target, Validspan) {simpovalidate.removehilight (target, MSG);
  var rule = simpovalidate.getrule (Validspan);
  var msg = validspan.attr ("msg"); var nullable = validspan.attr ("class"). IndexOf ("nullable") = = 1? False:true;

  Whether can be empty var to = validspan.attr ("to"); if (target) {//checkbox or radio if (target[0].tagname.tolowercase () = = "Input" && target.attr ("type") &&A mp (Target.attr ("type"). toLowerCase () = "checkbox" | | | target.attr ("type"). toLowerCase () = "Radio")
    {var checkedinput = $ ("input[name= '" + to + "']:checked");
      if (!nullable) {if (checkedinput.length = = 0) {simpovalidate.hilight (target, MSG);
     return false; }}//input or Select if (target[0].tagname.tolowercase () = "Input" | | target[0].tagname.tolowercase () = "s
    Elect ") {var val = target.val (); if (!nullable) {if ($.trim (val) = "") {Simpovalidate.hilight (target), msg);
     return false;
      } else {if ($.trim (val) = "") {Simpovalidate.removehilight (target, MSG);
     return true;
     } if (rule) {var reg = new RegExp (rule);
      if (!reg.test (val)) {Simpovalidate.hilight (target, MSG);
     return false;
    }} else if (target[0].tagname.tolowercase () = = "textarea") {var val = target.text ();
      if (!nullable) {if ($.trim (val) = "") {Simpovalidate.hilight (target, MSG);
     return false;
      } else {if ($.trim (val) = "") {Simpovalidate.removehilight (target, MSG);
     return true;
     } if (rule) {var reg = new RegExp (rule);
      if (!reg.test (val)) {Simpovalidate.hilight (target, MSG);
     return false;
 }}} return true;
  },//Get validation rules getrule:function (validspan) {var rule = validspan.attr ("ruleset");
   Switch ($.trim) {case ' int ': return this.rules.int; Case "number": Return this.rules.number;
    Default:return rule;
  Break
  },//red border and Error tip hilight:function (target, msg) {Target.addclass ("failvalid");
  Target.bind ("MouseOver", function (e) {simpovalidate.tips (target, MSG, e);
  });
  Target.bind ("Mouseout", function () {simpovalidate.removetips ();
 });
  },//Remove red border and error tip removehilight:function (target) {target.unbind ("mouseover");
  Target.unbind ("Mouseout");
  Target.removeclass ("Failvalid");
 Simpovalidate.removetips (); },//Display prompt tips:function (target, text, e) {var divtipsstyle = "Position:absolute; left:0; top:0; Background-color: #dceaf2; padding:3px; Border:solid 1px #6dbde4; Visibility:hidden; line-height:20px;
  ";

  $ ("Body"). Append ("<div class= ' div-tips ' style= '" + Divtipsstyle + "' >" + text + "</div>");
  var divtips = $ (". Div-tips");

  Divtips.css ("Visibility", "visible");
  var top = e.clienty + $ (window). scrolltop ()-Divtips.height ()-18;
  var left = E.clientx; DivTips.css ("Top", top);

  Divtips.css ("left", left);
   $ (target). MouseMove (function (e) {var top = E.clienty + $ (window). scrolltop ()-Divtips.height ()-18;
   var left = E.clientx;
   Divtips.css ("Top", top);
  Divtips.css ("left", left);
 });
 },//Remove hint Removetips:function () {$ (". Div-tips"). Remove ();

}
};
 $ (function () {simpovalidate.init ();});

How to use:

1, referencing CSS and JS (must refer to jquery):

<link type= "Text/css" href= "~/scripts/simpovalidate.css" rel= "stylesheet"/> <script "type=" text/
JavaScript "src=" ~/scripts/jquery-1.8.2.js "></script>
<script type=" Text/javascript "src=" ~/ Scripts/validateutil.js "></script>

2, form HTML code (partial code):

<table class= "table-test" cellpadding= "0" cellspacing= "0" style= "border-collapse:collapse; width:100%; " > <tr> <td> <input name= "C" value= "type=" text "/> <span class=" Valid nullable "rule=" in T "msg=" can be empty, please fill in the positive integer "></span> </td> </tr> <tr> <td> <input name=" D "value=" "Ty pe= "text"/> <span class= "valid" rule= "number" msg= "must fill in, please fill in the numbers" ></span> </td> </tr> <tr > <td> <select> <option value= "-1" >== Please select ==</option> <option value= "1" > is </ Option> <option value= "2" > "</option> </select> <span class=" valid "rule=" ^ (?! -1$). +$ "msg=" required "></span> </td> </tr> <tr> <td> <input name=" A "value=" 1 "Typ e= "checkbox"/> <span> more </span> <input name= "A" value= "2" type= "checkbox"/> <span> Less ;/span> <span class= "valid" rule= "" msg= "Required" to= "a" ></span> </td> </tr> <tr> <td> <input name= "B" value= "1" type= "RA
   Dio "/> <span> dog </span> <input name=" B "value=" 2 "type=" Radio "/> <span> cat </span>
   <span class= "valid" rule= "msg=" required "to=" B "></span> </td> </tr> <tr> <td> <textarea cols= "rows=" 5 "style=" height:50px; width:300px; " ></textarea> <span class= "Valid nullable" rule= "^ (. | \ n) {5,100}$ "msg=" is nullable and must be greater than or equal to 5 less than or equal to "></span> </td> </tr> </table>

3, the implementation of the Verification JS code:

Save Data
function Save () {
 if (Simpovalidate.valid ()) {//perform validation
  $ ("#frm"). Submit ();//Submit Form
 }
}

Effect Chart:

The above is the author himself to write a JavaScript form verification plug-in, hope to be able to help everyone.

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.