zoukankan      html  css  js  c++  java
  • 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:

    <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示例

    <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验证应用的原理、技巧

      demo

     

     

     

    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 ErrMsg
    • data-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 selector
    • data-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:

    1. Add the attribute data-val="true" to it which enables validation on the element 
    2. 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:

    <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
    • summary, displaying all validation errors

    Adding validation per element

    1. Add a validation result element, that will show when validation fails. This can be any element, normally a div or a span 
    2. 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
    3. 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:

    <span data-valmsg-for="color" data-valmsg-replace="true"></span>
    

    Adding a validation summary

    1. Add an element with data-valmsg-summary="true" to the form. Make sure it's inside the form!
    2. 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:

    <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:

    .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:

    .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:

    <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.

    // 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());
        }
    );
    
    <!--
    
    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>
    

      

    /* 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配合

    1. 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.
    2. The Model being used to drive the validatation
    3. The View that takes the model and uses the HTML Helpers to generate form elements
    4. The HTML generated by the view
    5. 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.
  • 相关阅读:
    springmvc视频学习
    两个数组a和b,都已经升序排列. 查找相同的元素?(要求不使用两层for循环)
    https Java SSL Exception protocol_version
    java多线程笔试题:设计4个线程,其中两个线程每次对j增加1,另外2个线程每次对j减少1.写出程序
    java多线程笔试题:子线程循环10次;接着主线程循环20次,接着又子线程循环10次,接着再回到主线程又循环20次,如此循环50次,请写出程序。
    R语言学习笔记
    重建二叉树-牛客网-剑指offer
    字符串替换空格-牛客网-剑指offer
    二维数组中的查找-牛客网-剑指offer
    牛客网-剑指offer-java版本解答目录(经自测)
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/9642382.html
Copyright © 2011-2022 走看看