Jquery.validate[.unobtrusive] and bootstrap implementation of ToolTip error analysis _jquery

Source: Internet
Author: User
Tags extend min

Similar articles have been, please see here, personal feeling slightly more complicated, a few days ago also intend to write a simple project to use, some key points recorded here. The final effect is as follows:

The back end uses ASP.net mvc5, and the front-end frames are: Jquery.validate, jquery.validate.unobtrusive, Requirejs, Bootstrap, all current/newer versions. Jquery.validate Needless to say, the current more popular front-end calibration components, jquery.validate.unobtrusive based on Jquery.validate, is to match asp.net mvc, Microsoft wrote itself, NuGet can find Microsoft.jQuery.Unobtrusive.Validation installation, specific how to use please continue to look down.

First in the background we define entity classes:

<summary>///Factory Information///</summary> public class Manufacturer:operatedmodel {[Key] [databasegenerate
  D (databasegeneratedoption.identity)] public int ID {get; set;}
  <summary>///Credit Code/Registration number///</summary> [Required (errormessage = "Credit Code/registration number cannot be empty")] [MaxLength (30)]
  public string Enterpriseno {get; set;} <summary>///Enterprise Name///</summary> [Required (errormessage = "Enterprise name cannot be empty")] public string Enterprisena
  me {get; set;} <summary>///Registered Address///</summary> [Required (errormessage = "Registered address cannot be NULL")] public string Registeredad
  Dress {get; set;}  <summary>///Legal entity///</summary> [Required (errormessage = "legal entity cannot be empty")] public string Artificialperson
  {get; set;} <summary>///person in charge///</summary> [Required (errormessage = "owner cannot be empty")] public stri
  ng PIC {get; set;}
  [Required (errormessage = "Cell phone number cannot be empty")] [RegularExpression (Regexlib.mobile,errormessage = "Phone number format is not correct")] public string Mobile {get; set;}
  [EmailAddress] public string Email {get; set;}
  <summary>///Shop Number///</summary> public string Shopnumber {get; set;}
  <summary>///Store Manager name///</summary> public string Storemanagername {get; set;} <summary>///store Manager Contact///</summary> [RegularExpression (Regexlib.mobile, errormessage= "Incorrect format of mobile phone number")
  ] public string Storemanagernumber {get; set;}
  <summary>///main license, three certificates in Oneness Business license///</summary> public string Mainlicence {get; set;}
  <summary>///JSON, other licenses, such as production licenses///</summary> public string Otherlicence {get; set;} <summary>///Date///</summary> [Required (errormessage = "Can't be Empty")] public DateTime enterdate
  {get; set;}  <summary>///Departure date///</summary> [Required (errormessage = "Due date cannot be empty")] public DateTime quitdate { Get Set }
  ///<summary>///manufacturers can present balance///</summary> public decimal Balance {get; set;}}
 

Entity attributes have the attribute form of the validation rules, when the user submits a model to the back-end action, the MVC framework will automatically help us complete the verification work, so the backend development is very happy. However, before the data submission, the front end is also necessary for the first round of the check, if the use of jquery.validate, then need to write in JS or tags again similar rules, can not reuse the back end of the code? We take attribute Enterpriseno as an example and write in cshtml:

@Html. Textboxfor (M => M.basicinfo.enterpriseno, new {placeholder = "required", @class = "Form-control"})

The resulting HTML is as follows:

<input class= "Form-control" data-val= true "data-val-maxlength=" field Enterpriseno must be a string or array type with a maximum length of "30". "Data-val-maxlength-max=" "data-val-required=" Credit Code/registration number can not be empty "id=" Basicinfo_enterpriseno "Name=" Basicinfo.enterpriseno "placeholder=" required "value=" "data-original-title=" "title=" "type=" text >

tags automatically add a lot of data-at the beginning of the property, data-val that the control needs to check, the other data-at the beginning of a series of validation rules and failure of the error message, the error message can be customized, otherwise the framework will give you a class like "field Enterpriseno Must be a string or array type with a maximum length of 30. "This machine translation language. Of course these attributes jquery.validate is not recognized, to let jquery.validate know, you need to jquery.validate.unobtrusive.

Now let's say how these JS work together.

The new version of Jquery.validate already supports AMD mode, so it can be loaded directly using Requirejs, jquery.validate.unobtrusive is no good, need shim configuration, code:

Require.config ({
      baseurl: '/scripts ',
      paths: {
        "jquery": ' Jquery-2.2.3.min ', '
        Knockout ': ' knockout-3.4.0 ',
        "bootstrap": '.. /components/bootstrap/3.3.6/js/bootstrap.min ', ' Validate ': ' Jquery.validate ',
        ' validateunobtrusive ': ' Jquery.validate.unobtrusive.min '
      },
      shim: {
        ' bootstrap ': {
          deps: [' jquery '],
          exports: ' Bootstrap '
        },
        ' validateunobtrusive ': {
          deps:[' validate '],
          exports: ' Validateunobtrusive '
        }
      }
    });

After the configuration, require in the page, click submit button submitted form, each JS began to function. But in addition to the focus will fall on the first validation failed control, there seems to be no other effect, even jquery.validate default to display the error message behind the control (Errorplacement function) are not, are you kidding me? In fact, this is because jquery.validate.unobtrusive covers the Errorplacement configuration items (see the source of the Attachvalidation function), for us instead of saving a process. Because ToolTip HTML markup is dynamically generated by Bootstrap, Errorplacement is not for us, refer to the link at the beginning of this article, select the Overwrite showerrors function, The core code is as follows (Tooltipvalidator.js):

define ([' validateunobtrusive '], function () {function tooltipvalidator () {} Tooltipvalidator.prototype = {ini T:function (Validatoroptions, tooltipoptions) {tooltipoptions = Tooltipoptions | |
      {}; validatoroptions = Validatoroptions | |

      {};

      This._tooltipoptions = $.extend ({}, {placement: ' top '}, Tooltipoptions, {animation:false});
        This._validatoroptions = $.extend ({}, {//errorplacement:function (error, Element) {///does nothing }, Showerrors:function (Errormap, errorlist) {for (var i = 0; i < this.successList.length ;
            i++) {var success = this.successlist[i];
            $ (This.successlist[i]). ToolTip (' Destroy ');
          $ (this.successlist[i]). Parents (' Div.form-group '). Removeclass (' Has-error ');
            for (var i = 0; i < errorlist.length i++) {var errorelement = $ (errorlist[i].element); Errorelement.parents (' Div.form-group '). addclass (' Has-error ');
          Errorelement.attr (' Data-original-title ', errorlist[i].message). ToolTip (' Show ');
        }, Submithandler:function (form) {return false;
      }, Validatoroptions) This._configtooltip ();
    This._configvalidator ();
    }, _configtooltip:function () {$ (' [data-val= ' true '] '). ToolTip (This._tooltipoptions);
      }, _configvalidator:function () {$.validator.setdefaults (this._validatoroptions);
    $.validator.unobtrusive.parse (document);
Return to New Tooltipvalidator (); });

So we can execute the Tooltipvalidator.init in the Require callback function, do not need to write the logic separately, so the front end classmate also happy smile. Here's another place to be aware that you see the 49th line of code, which is the procedure for initializing jquery.validate.unobtrusive. Originally jquery.validate.unobtrusive in its code already has $ (function () {$jQval. Unobtrusive.parse (document);}); However, since $.ready is executed after the DOM element is loaded (digression: Not render complete), it will be completed before Tooltipvalidator has a chance to _configvalidator, causing our configuration entry to be invalid (if it is not in a single page refresh application, It is found that the configuration entry works when the local page is loaded again, because the $.ready is executed only at the initial load, and the require callback executes every time the load is loaded. There are two solutions: 1, let jquery.validate.unobtrusive rely on tooltipvalidator;2, remove the $ in jquery.validate.unobtrusive JQval.unobtrusive.parse (document); This is the 2nd choice.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.