Jquery Validation
相关js
The heavy lifting is done by the jQuery Validation plugin, which depends on (you guessed it) jQuery.
In order for the whole thing to become unobtrusive, you need jQuery UnobtrusiveValidation. So all in all you need:
1 2 3 | <script src= "//code.jquery.com/jquery-1.11.0.min.js" ></script> <script src= "//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js" ></script> <script src= "//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js" ></script> |
html示例
1 | < input type="text" name="color" data-val="true" data-val-required="Please enter a color" /> |
jquery.validate.unobtrusive:总体介绍
MVC3 unobtrusive validate:介绍
jQuery.Validation.Unobtrusive.Native:介绍
自定义验证
Overriding Unobtrusive Client Side Validation Settings in ASP.NET MVC 3:如何自定义js验证
What is Unobtrusive Validation? - ASP.NET MVC Demystified :MVC验证应用的原理、技巧
html attr介绍
data-val="true"
: enable unobtrusive validation on this element (should be on every input element you want to validate)data-val-required="ErrMsg"
: makes the input required, and shows the ErrMsgdata-val-length="ErrMsg"
,data-val-length-min="5"
,data-val-length-max="15"
: sets required string length and associated error message.data-val-number="ErrMsg"
: makes a field required to be a number.data-val-date="ErrMsg"
: requires a field to be a date (I do not recommend this, as it accepts too much – I prefer to use regex).data-val-equalto="ErrMsg"
,data-val-equalto-other="Fld"
: requires one field to match the other (such as password confirm. Fld is a jQuery selectordata-val-regex="ErrMsg"
,data-val-regex-pattern="^regex$"
: Requires the field to match the regex pattern.data-val-email="ErrMsg"
: requires a field to be a email (I do not recommend this, as it accepts too much – I prefer to use regex).data-val-url="ErrMsg"
: requires a field to be a url (I do not recommend this, as it accepts too much – I prefer to use regex).
- data-val specifies that this input needs validation.
- data-val-required is the error message to be displayed if a value is not provided.
- data-valmsg-for is the name of the input associated to the error message(s) being displayed.
- data-valmsg-replace specified whether error messages are to be replaced within this element.
element验证
Unobtrusive validation is called just that (unobtrusive) because once the scripts are loaded, it's entirely attribute-based.
The form tag itself can stay as it is, but validation has to be added to every input element that needs to be validated.
Here's how you set it up per element:
- Add the attribute data-val="true" to it which enables validation on the element
- Add one or more validation attributes, such as data-val-required or data-val-min.
This will cause the unobtrusive validator to perform its magic, which basically consists of juggling css styles on these elements.
Here's a text input with validation:
1 | < input type="text" name="color" data-val="true" data-val-required="Please enter a color" /> |
展示验证信息
Of course, the validation results (which are in fact validation error messages) have to appear somewhere - and you have to create elements for that.
There are two ways to display validation errors
- A validation error message per element
- A summary, displaying all validation errors
Adding validation per element
- Add a validation result element, that will show when validation fails. This can be any element, normally a div or a span
- Give it the data-valmsg-for attribute. Set the value of the attribute to the name (not the id!) of the element it displays a result for
- Add data-valmsg-replace="true" if you want the contents of the result element to be set to the validation error when one occurs. Normally, this should be the case. If not, the contents will be left alone, so the won't be informative
The color text box in the previous sample could have the following validation result element:
1 | < span data-valmsg-for="color" data-valmsg-replace="true"></ span > |
Adding a validation summary
- Add an element with data-valmsg-summary="true" to the form. Make sure it's inside the form!
- Important: Give this element an (empty) ul-element. This element will receive li-elements for every validation error that occurs. Without it, the validation summary will not work
This is how a simple validation summary element might look:
1 2 3 | < div data-valmsg-summary="true"> < ul ></ ul > </ div >v |
validation summaries have a big drawback though: their contents are not updated when the validity of elements changes while tabbing around.
样式
Unobtrusive validation works by setting and removing attributes on the element to be validated, and additionally changing the contents of the elements used to display validation results.
- Validated elements (marked with data-val) get one of the class names input-validation-erroror valid added to them, depending on their validity. Additionally, a bunch of aria-attributes get added and removed
- The validation result elements (those marked with data-valmsg-for) get the class name field-validation-error or field-validation-valid
- The validation summary element (marked with data-valmsg-for) gets the class name validation-summary-errors added when it contains validation errors; if not, the class name is removed
So, to style you validated elements you could use:
1 2 3 | .input-validation-error { border: solid 1px red; } |
This would result in all elements that have failed validation (i.e. that are invalid now) to show a red border.
The validation error elements can be styled like this:
1 2 3 | .field-validation-error { color: red; } |
This makes all error messages associated with validated elements red.
验证策略
Validate-on-tab
The default unobtrusive validation strategy is to do nothing when the page is first loaded.
Only when the user tabs away from an input element, it's validated for the first time.
This is an excellent strategy that we're all used to: when the page is loaded, all form elements have their initial value - which will be invalid for most items, simply because the user hasn't entered anything into them yet. But because he has had no opportunity to do anything about that, we're not going to bother him with the results.
Using this strategy, we have to make sure the individual validation result elements are in the right "state": they must appear to be valid. This can easily be achieved by giving them the field-validation-valid class.
Alternatively, you can rely on the fact that your validation result elements will be empty, and therefore not take up any space. In that case there's no need for action.
Start validation on page load
Occasionally, this is not enough. Sometimes you want the form to show which elements are invalid as soon as the page is loaded.
Imagine a user's profile is incomplete - he needs to enter an email address.In that case, we can display his profile with all data available and show the email text input as invalid only if it's still empty. Do this with a startup script like this, which calls valid() on all forms:
1 2 3 4 | < script >$(function() { $("form").valid(); }); </ script > |
The selector used (in this case form) determines which forms are validated - in this case, all forms. This will also populate any validation summaries!
示例
I've made a JSFiddle with a simple form with validation. It asks for a name and demands you provide one, and that it's longer than two letters. Also, you must enter your age, which must lie between 10 and 120.
1 2 3 4 5 6 7 8 9 | // Enable this line to validate the form on page load // $("form").valid(); // Display the result of the form. Only called when validation succeeds! $( "input[type='submit']" ).click( function (event) { event.preventDefault(); // Do not actually submit alert( "You entered " + $( "#your-name-id" ).val() + ", age " + $( "#your-age-id" ).val()); } ); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!-- Example of a simple jQuery Unobtrusive Validation form See http://www.mobzystems.com/blog/setting-up-jquery-unobtrusive-validation/ --> < form > < div data-valmsg-summary="true"> < ul ></ ul > </ div > < div > < label for="your-name-id">Your name:</ label > < input type="text" name="yourname" id="your-name-id" placeholder="Please enter your name" data-val="true" data-val-required="Please enter a name" data-val-length="Please enter more than two letters" data-val-length-min="2" /> < span data-valmsg-for="yourname" data-valmsg-replace="true" /> </ div > < div > < label for="your-age-id">Your age [hint: 10-120]:</ label > < input type="text" name="yourage" id="your-age-id" placeholder="Please enter your age" data-val="true" data-val-required="Please enter an age" data-val-number="Please enter a valid number" data-val-range="You must be between 10 and 120 years old" data-val-range-min="10" data-val-range-max="120" /> < span data-valmsg-for="yourage" data-valmsg-replace="true" /> </ div > < p > < input type="submit" value="Go" /> </ p > </ form > < div > < a href="http://www.mobzystems.com/blog/setting-up-jquery-unobtrusive-validation/">View blog entry</ a > </ div > < script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></ script > < script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></ script > |
1 2 3 4 5 6 7 8 9 | /* Show validation results in red */ .field-validation-error { color : red ; } /* Change background color of invalid text inputs to light red */ input[type= "text" ].input-validation-error { background-color : #fcc ; } |
MVC配合
- A working demo so you can see the validation in action. To trigger the validation on a demo then just click on the Submit button. When / if all the validations have passed and the form submitted then the user will be presented with a message confirming that the form is valid.
- The Model being used to drive the validatation
- The View that takes the model and uses the HTML Helpers to generate form elements
- The HTML generated by the view
- The JavaScript used to initialise the validation
Client-Side vs Server-Side Validation - Do We Need Both?
Absolutely! In fact, we only actually need server-side validation, since client-side can be disabled by the browser.
However, handling both scenarios provides a nice graceful degredation where the user will still get the validation they need, in the nicest way their browser provides.
- data-val specifies that this input needs validation.
- data-val-required is the error message to be displayed if a value is not provided.
- data-valmsg-for is the name of the input associated to the error message(s) being displayed.
- data-valmsg-replace specified whether error messages are to be replaced within this element.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?