English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Similar articles already exist, please see here. I feel that it is a bit complex, and I also plan to write a simple one for the project recently, some key points are recorded here. The final effect is as follows:
Backend uses Asp.net mvc5Among the front-end frameworks are: jQuery.validate, jQuery.validate.unobtrusive, requirejs, Bootstrap, all of which are the most/The newer version. jQuery.validate is not to be mentioned, it is currently a popular front-end validation component; jQuery.validate.unobtrusive is based on jQuery.validate, designed to work with Asp.net mvc, written by Microsoft itself, you can find it in NuGet as Microsoft.jQuery.Unobtrusive.Validation. How to use it will be explained further below.
Firstly, in the background, we define the entity class:
/// summary> /// Manufacturer Information /// </summary> public class Manufacturer : OperatedModel { [Key] [DatabaseGenerated(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 EnterpriseName { get; set; } /// summary> /// registered address /// </summary> [Required(ErrorMessage = "Registered address cannot be empty")] public string RegisteredAddress { get; set; } /// summary> /// legal person /// </summary> [Required(ErrorMessage = "Legal person cannot be empty")] public string ArtificialPerson { get; set; } /// summary> /// person in charge, responsible person /// </summary> [Required(ErrorMessage = "Person in charge cannot be empty")] public string PIC { get; set; } [Required(ErrorMessage = "Mobile phone number cannot be empty")] [RegularExpression(RegexLib.Mobile, ErrorMessage = "Incorrect mobile phone number format")] public string Mobile { get; set; } [EmailAddress] public string Email { get; set; } /// summary> /// shop number /// </summary> public string ShopNumber { get; set; } /// summary> /// store manager's name /// </summary> public string StoreManagerName { get; set; } /// summary> /// contact information of store manager /// </summary> [RegularExpression(RegexLib.Mobile, ErrorMessage="Incorrect mobile phone number format")] public string StoreManagerNumber { get; set; } /// summary> /// main license, unified business license of three certificates /// </summary> public string MainLicence { get; set; } /// summary> /// json, other licenses, such as production license /// </summary> public string OtherLicence { get; set; } /// summary> /// Entry date /// </summary> [Required(ErrorMessage = "The入驻date cannot be empty")] public DateTime EnterDate { get; set; } /// summary> /// Exit date /// </summary> [Required(ErrorMessage = "The closing date cannot be empty")] public DateTime QuitDate { get; set; } /// summary> /// Factory withdrawable balance /// </summary> public decimal Balance { get; set; } }
Each property of the entity has an Attribute-style validation rule, when a user submits a Model to the backend Action, the MVC framework will automatically complete the validation work, which makes backend development very happy. However, it is also necessary for the front-end to perform the first round of validation before data submission. If using jquery.validate, it is necessary to write similar rules again in js or tags, can we reuse the existing code from the backend? Let's take the property EnterpriseNo as an example, and write in cshtml:
@Html.TextBoxFor(m => m.BasicInfo.EnterpriseNo, new { placeholder = "Mandatory item", @class = "form-control" })
The generated html is as follows:
<input class="form-control" data-val="true" data-val-maxlength="The field EnterpriseNo must be the maximum length of"30" of a string or array type.\" data-val-maxlength-max="30" data-val-required="Credit Code/The registration number cannot be empty" id="BasicInfo_EnterpriseNo" name="BasicInfo.EnterpriseNo" placeholder="Mandatory item" value="" data-original-title="" title="" type="text">
Many data are automatically added to the label-properties starting with data-val indicates that the control needs to be validated, other data-The beginning is a series of validation rules and error messages when failed, the error message can be customized, otherwise the framework will generate something like "The field EnterpriseNo must be the maximum length of"30 is a string or an array type. Of course, these properties are not recognized by jquery.validate, and to make them recognizable, we need to call on jquery.validate.unobtrusive.
Now let's talk about how these JavaScript files work together.
The new version of jquery.validate already supports AMD mode, so it can be directly loaded using requirejs, but jquery.validate.unobtrusive cannot, and requires shim configuration, as shown in the code:
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 configuration, require it on the page, and then click the submit button to submit the form. At this point, the various JavaScript files begin to take effect. However, it seems that there is no other effect besides the focus falling on the first control that fails validation, and even the default error information display (errorPlacement function) of jquery.validate is missing. Are you kidding me? In fact, this is because jquery.validate.unobtrusive overrides the errorPlacement configuration option (see the attachValidation function in the source code), which is actually a process saved for us. Since the tooltip's HTML tag is dynamically generated by bootstrap, errorPlacement is not suitable for us. Refer to the link at the beginning of this article, and choose to override the showErrors function, the core code of which is as follows (tooltipvalidator.js):
define(['validateunobtrusive'], function () {}} function TooltipValidator() {} TooltipValidator.prototype = { init: function (validatorOptions, tooltipOptions) { tooltipOptions = tooltipOptions || {}; validatorOptions = validatorOptions || {}; this._tooltipOptions = $.extend({}, { placement: 'top' }, tooltipOptions, { animation: false }); this._validatorOptions = $.extend({}, { //errorPlacement: function (error, element) { // // do 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 new TooltipValidator(); });
This way, we can execute tooltipvalidator.init in the require callback function without writing additional logic, and the front-end colleagues also smiled happily. There is also one thing to note, everyone sees the number49Line of code, this is the initialization step for jquery.validate.unobtrusive. Originally, jquery.validate.unobtrusive already has $(function () { $jQval.unobtrusive.parse(document); }); However, due to $.ready executing after the Dom elements are loaded (by the way: not after rendering), it will complete before tooltipvalidator has a chance to _configValidator, resulting in our configuration options being invalid (if it's in a single-page refreshless application, you will find that the configuration options are valid when loading the partial page again, because $.ready only executes on the initial load, while require callbacks execute each time a load occurs). There are two solutions:1Make jquery.validate.unobtrusive depend on tooltipvalidator;2Remove $jQval.unobtrusive.parse(document); from jquery.validate.unobtrusive. Here, we choose the following:2species.
Thank you for reading and hope it can help everyone. Thank you for your support of this website!
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, the website will immediately delete the content suspected of infringement.