jqueryvalidation

最後更新: 2015-06-17

homepage: http://jqueryvalidation.org/

 

Example

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>Please provide your name, email address (won't be published) and a comment</legend>
    <p>
      <label for="cname">Name (required, at least 2 characters)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (optional)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">Your comment (required)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>

<script>
    $("#commentForm").validate();
</script>

 


設定 validation

 

element -> rule -> method

method: implements the logic to validate an element

rule: associates an element with a validation method
( 用 methods "required", "email" ... )

 

Plugin methods:
    validate() – Validates the selected form.
    valid() – Checks whether the selected form or selected elements are valid.
    rules() – Read, add and remove rules for an element.

Custom selectors
    :blank – Selects all elements with a blank value.
    :filled – Selects all elements with a filled value.

    

    
$("#myform").validate({
 submitHandler: function(form) {
   form.submit();
 }
});

 

 


validate 放在 <head> 內

<script>
    $.validator.setDefaults({
        submitHandler: function() {
            alert("submitted!");
        }
    });

    $().ready(function() {
        // validate the comment form when it is submitted
        $("#commentForm").validate();

        // validate signup form on keyup and submit
        $("#signupForm").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2
                },
                password: {
                    required: true,
                    minlength: 5
                },
                confirm_password: {
                    required: true,
                    minlength: 5,
                    equalTo: "#password"
                },
                email: {
                    required: true,
                    email: true
                },
                topic: {
                    required: "#newsletter:checked",
                    minlength: 2
                },
                agree: "required"
            },
            messages: {
                firstname: "Please enter your firstname",
                lastname: "Please enter your lastname",
                username: {
                    required: "Please enter a username",
                    minlength: "Your username must consist of at least 2 characters"
                },
                password: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long"
                },
                confirm_password: {
                    required: "Please provide a password",
                    minlength: "Your password must be at least 5 characters long",
                    equalTo: "Please enter the same password as above"
                },
                email: "Please enter a valid email address",
                agree: "Please accept our policy"
            }
        });

        
        // propose username by combining first- and lastname
        $("#username").focus(function() {
            var firstname = $("#firstname").val();
            var lastname = $("#lastname").val();
            if (firstname && lastname && !this.value) {
                this.value = firstname + "." + lastname;
            }
        });

        
        //code to hide topic selection, disable for demo
        var newsletter = $("#newsletter");
        
        // newsletter topics are optional, hide at first
        var inital = newsletter.is(":checked");
        var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
        var topicInputs = topics.find("input").attr("disabled", !inital);
        
        // show when newsletter is checked
        newsletter.click(function() {
            topics[this.checked ? "removeClass" : "addClass"]("gray");
            topicInputs.attr("disabled", !this.checked);
        });
        
    });
    </script>
    
    

    
List of built-in Validation methods

required: true

minlength: 3
maxlength
rangelength

min
max
range: [13, 23]

url
email
dateISO               # 2015-09-20
digits
equalTo: "#password"

 


Add a custom validation method

jQuery.validator.addMethod( name, method [, message ] )

First argument: Current value.
Second argument: Validated element.
Third argument: Parameters.

i.e.

jQuery.validator.addMethod("math", function(value, element, params) {
  return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));

jQuery.validator.format( template [, argument, argumentN…] )

template
Type: String
The string to format.

Replaces {n} placeholders with arguments.

i.e.

var template = jQuery.validator.format("{0} is not a valid value");
// later, results in 'abc is not a valid value'
alert(template("abc"));

pattern method

src/additional/pattern.js

to validate a field against a regular expression.

http://regexlib.com/DisplayPatterns.aspx

i.e.

jQuery.validator.addMethod("laxEmail", function(value, element) {
  // allow any non-whitespace characters as the host part
  return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@(?:\S{1,63})$/.test( value );
}, 'Please enter a valid email address.');

optional

The this.optional check is basically checking to see if the field is blank or not before evaluating whether or not it meets the rule.

If the field is optional, the method returns successfully immediately;
if it's required, the method returns failure immediately.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Creative Commons license icon Creative Commons license icon