JS realizes the _javascript technique of the form plug-in that supports AJAX verification

Source: Internet
Author: User
Tags tagname

This article for you to share a form verification plug-in, support Ajax verification, easy to use.
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 () {$ (". Valid"). each (function () {//Traverse span if ($ (this) [0].tagname.tolower
        Case () = = "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 () {Simpovalidate.ajaxcheckresult = true;

    var bl = true; $ (". Valid"). each (function () {//Traverse span if ($ (this) [0].tagname.tolowercase () = "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 && simpovalidate.ajaxcheckresult;

    },//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");

    var ajaxaction = validspan.attr ("ajaxaction"); if (target) {//checkbox or radio if (target[0].tagname.tolowercase () = = "Input" && target.attr ("type") &  amp;& (target.attr ("type"). toLowerCase () = "checkbox" | | | target.attr ("type"). toLowerCase () = "Radio")) {varCheckedinput = $ ("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.tolowe
        Rcase () = = "Select") {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;
        } if (ajaxaction) {Simpovalidate.ajaxcheck (target, Val, ajaxaction); } 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;
        } if (ajaxaction) {Simpovalidate.ajaxcheck (target, Val, ajaxaction);
  }} return true; }, Ajaxcheckresult:true, Ajaxcheck:function (target, value, ajaxaction) {var targetName = target.attr ("name")
    ;
    var data = new Object ();

    Data[targetname] = value; $.ajax ({url:ajaxaction, type: "POST", Data:data, Async:false, Success:function (data) {if (Data.data = = True) {simpovalidate.removehilight (target);
          else {Simpovalidate.ajaxcheckresult = false;
        Simpovalidate.hilight (target, data.data);
  }
      }
    });
    },//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 (); },//Show Prompt tIps:function (target, text, e) {var divtipsstyle = "Position:absolute; z-index:99999; left:0; top:0; Background-color: #dceaf2; padding:3px; Border:solid 1px #6dbde4; Visibility:hidden; line-height:20px;
    font-size:12px; ";

    $ ("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:
Edit page:

@using Model.suya;
  @{viewbag.title = "ADD";
Layout = "~/views/shared/_layout.cshtml";
  } @{list<sys_post> postlist = (list<sys_post>) viewdata["Postlist"];
Sys_post post = (sys_post) viewdata["POST"];
      } <script type= "Text/javascript" > $ (function () {//Departmental tree $ (' #dept '). Combotree ({url: ' Getdepttree ', Required:false, Checkbox:true, Onloadsuccess:function () {$ (' #dept '). Combotree (' SetValue ', "@
      (Post.depcode) ");

    }
    }); 
      Action result $ ("#ifrm"). Load (function (data) {var data = eval ("+ $ (" #ifrm "). Contents () (" Body "). HTML () +") "
      alert (data.msg);
    if (Data.ok) back ();

    });
  $ ("Select[name= ' Postlevel ']"). Find ("Option[value= ' @ (post.postlevel)"). attr ("Selected", "Selected");

  });
    Save function Save () {if (valid ()) {$ ("#frm"). Submit ();
    }//Verify function valid () {var dept = $ ("input[name= ' dept ']"); if (!dept.val ()) {Simpovalidate.hilight(Dept.parent (), "Please select Department");
    else {simpovalidate.removehilight (dept.parent ());
  return Simpovalidate.valid ();
    //Return function back () {parent.$ (' #ttTab '). Tabs (' Select ', ' post Management ');
    var tab = parent.$ (' #ttTab '). Tabs (' getselected ');
    Tab.find ("iframe"). Contents (). Find ("#btnSearch"). Click ();
  parent.$ ("#ttTab"). Tabs (' Close ', ' revise post information '); 
  } </script> <div class= "Tiao" > <input type= "button" class= "Submit_btn" value= "Save" onclick= "Saving ()"/> <input type= "button" class= "Submit_btn" value= "return" onclick= "Back ()"/> </div> <iframe id= "ifrm" name= "if RM "style=" Display:none; " ></iframe> <form id= "frm" method= "post" enctype= "Multipart/form-data" action= "/hr/postmanage/saveedit"? id=@ (post.id) "target=" ifrm "> <div class=" adminmaincontent "> <div class=" box "> <div class=" box-tit Le "> Basic information </div> <div class=" box-content "> <table cellpadding=" 0 "cellspacing=" 0"class=" detail "width=" 100% "> <tr> <td class=" title "> <span class=" MST "&G T;*</span> Post name: </td> <td style= "width:35%;"  > <input type= "text" class= "Xinxi_txt" name= "Postname" value= "@post. Postname"/> <span class= "valid" "msg=" must be filled out, and can not exceed the length of "rule=" ^ (. | \ n) {0,50}$ "></span> </td> <td class=" title "> <span class=" MST "> *</span> Post No.: </td> <td style= "width:35%;"  > <input type= "text" class= "Xinxi_txt" name= "postcode" value= "@post. Postcode"/> <span class= "valid" "msg=" must be filled out, and can not exceed the length of "rule=" ^ (. |
        \ n) {0,20}$ "ajaxaction="/hr/postmanage/ajaxcheckpostcode?id= @post. Id "> </span> </td> </tr> <tr> <td class= "title" > <span class= "MST" &GT;*&LT;/SPAN&G T Subordinate Department:;/td> <td style= "width:35%;"
          > <input type= "text" name= "Depcode" id= "dept" class= "Easyui-combotree" style= "height:30px;"/> </td> <td class= "title" > <span class= "MST" >*</span> Reporting object: < /TD> <td style= "width:35%;" > <select class= "Xueli" name= "Reportpostcode" id= "Agreementtype" > <option value= "" s
                Elected= "Selected" >== Please select ==</option> @foreach (sys_post item in postlist) { if (Item.postcode = = Post.reportpostcode) {<option value= "@item. Postcode" SELECT Ed= "selected" > @item .postname</option>} else {&L T;option value= "@item. Postcode" > @item .postname</option>}} </select > <span class= "valid" msg= "Please select the contract classification" >
          </td> </tr> <tr> <td class= "title" > <span clas s= "MST" >*</span> position level: </td> <td style= "width:35%;" > <select class= "Xueli" name= "Postlevel" > <option value= "" selected= "selected" >== Please select ==</option> <option value= "1" >1</option> <option value= "2" >2</op
              Tion> <option value= "3" >3</option> <option value= "4" >4</option> <option value= "5" >5</option> <option value= "6" >6</option> 
          ;/select> <span class= "valid" msg= "Please select position level" > </td> <td class= "title" > </td> <td style= "width:35%;" > </td> </tr> <tr> <td class= "title" > <span class= "MST" >*</span> notes: </td> <td colspan= "3" style= "width:35%;" > <textarea name= "Remarks" style= "width:500px;" > @post .remarks</textarea> <span class= "valid" msg= "length shall not exceed" rule= "^ (. | \ n) {0,500}$ "></span> </td> </tr> </table> </div> &LT;/DIV&G
T

 </div> </form>

Effect Chart:

The above is the entire content of this article, I hope to help you learn.

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.