标签:generic tle after The fill lex however inline security
效果:
Validate forms like you‘ve never validated before!
自定义Validate:
集成好的、拿来即用的Validate
<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>
A single line of jQuery to select the form and apply the validation plugin, plus a few annotations on each element to specify the validation rules.
API
two terms are used very often, so it‘s important that you know their meaning in the context of the validation plugin:
List of built-in Validation methods:A set of standard validation methods is provided:
required
– Makes the element required.remote
– Requests a resource to check the element for validity.minlength
– Makes the element require a given minimum length.maxlength
– Makes the element require a given maximum length.rangelength
– Makes the element require a given value range.min
– Makes the element require a given minimum.max
– Makes the element require a given maximum.range
– Makes the element require a given value range.step
– Makes the element require a given step.email
– Makes the element require a valid emailurl
– Makes the element require a valid urldate
– Makes the element require a date.dateISO
– Makes the element require an ISO date.number
– Makes the element require a decimal number.digits
– Makes the element require digits only.accept
– Makes a file upload accept only specified mime-types.creditcard
– Makes the element require a credit card number.extension
– Makes the element require a certain file extension.phoneUS
– Validate for valid US phone number.require_from_group
– Ensures a given number of fields in a group are complete.$.validator.methods
propertyrules
).
// alias required to cRequired with new message $.validator.addMethod("cRequired", $.validator.methods.required, "Customer name required"); // alias minlength, too $.validator.addMethod("cMinlength", $.validator.methods.minlength, // leverage parameter replacement for minlength, {0} gets replaced with 2 $.validator.format("Customer name must have at least {0} characters")); // combine them both, including the parameter for minlength $.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });
<input name="customer1" class="customer"> <input name="customer2" class="customer"> <input name="customer3" class="customer">
You can also reuse existing methods inside other custom methods, to reuse certain implementations.
jQuery.validator.methods.email.call(this, email, element)
Plugin methods
This library adds three jQuery plugin methods, the main entry point being the validate
method:
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
This library also extends jQuery with three custom selectors:
:blank
– Selects all elements with a blank value.:filled
– Selects all elements with a filled value.:unchecked
– Selects all elements that are unchecked.Validation event
The goal of these interactions is to provide feedback as early as possible, whilst avoiding user annoyance.
Displaying error messages before the user had the chance to even type something is not helpful.
onsubmit
). onkeyup
).onfocusout
).
The validate method returns a Validator object that has a few public methods that you can use to trigger validation programmatically or change the contents of the form
The validator object has more methods, but only those documented here are intended for usage.
Validator.form()
– Validates the form.Validator.element()
– Validates a single element.Validator.resetForm()
– Resets the controlled form.Validator.showErrors()
– Show the specified messages.Validator.numberOfInvalids()
– Returns the number of invalid fields.Validator.destroy()
– Destroys this instance of validator.
There are a few static methods on the validator object:
jQuery.validator.addMethod()
– Add a custom validation method.jQuery.validator.format()
– Replaces {n} placeholders with arguments.jQuery.validator.setDefaults()
– Modify default settings for validation.jQuery.validator.addClassRules()
– Add a compound class method.
An error message displays a hint for the user about invalid elements, and what is wrong.
There are four ways to provide error messages.
messages
).
All validation rules included here provide a default error message which you can use for prototyping,because it is used when no specific message is provided.
The priorities are as follows:
When using data attributes, you can set a generic message for all rules, or specific messages per rule:
<input required data-msg="Please fill this field"> <input data-rule-minlength="2" data-rule-maxlength="4" data-msg-minlength="At least two chars" data-msg-maxlength="At most fours chars">
Error messages are handled via label elements with an additional class (option errorClass
).
The link between the message and the invalid element is provided via the labels for attribute.
When provided in the markup, they are shown and hidden accordingly, and otherwise created on demand.
By default, labels are created after the invalid element, this is also customizable (option errorPlacement
).
It is also possible to put them into an error container (option errorLabelContainer
).
To use a different element then a label, specify the errorElement
option.
In addition to field-specific messages you can display a general "your form is invalid, please fix the highlighted fields!" message in a container anywhere on your page,
eg. above the form (option errorContainer
).
The container is shown and hidden when errors occur and are fixed accordingly.
The container for error labels (option errorLabelContainer
) can also be nested inside the error container.
By default, the first invalid element in a form is focused after submitting a form with invalid elements.
To prevent confusion on the behalf of the user, the plugin remembers the element that had focus when the form was submitted, and refocuses that element.
That way the user can try to fill out elements of the form at the end, without being forced to focus them again and again. This can be disabled (option focusInvalid
).
provides detailed discussion of the design and ideas behind the plugin,
explaining why certain things are as they are.
It covers the features in more detail than the API documentation, which just briefly explains the various methods and options available.
When you have a name attribute like user[name], make sure to put the name in quotes.
More details in the General Guidelines.
If your form consists of fields using names that aren‘t legal JavaScript identifiers, you have to quote those names when using the rules
option:
$("#myform").validate({ rules: { // no quoting necessary name: "required", // quoting necessary! "user[email]": "email", // dots need quoting, too! "user.address.street": "required" } });
Another common problem occurs with this code:
$("#myform").validate({ submitHandler: function(form) { // some other code // maybe disabling submit button // then: $(form).submit(); } });
This results in a too-much-recursion error:
$(form).submit()
triggers another round of validation, resulting in another call to submitHandler, and voila, recursion.
Replace that with form.submit(), which triggers the native submit event instead and not the validation.
So the correct code looks slightly different:
$("#myform").validate({ submitHandler: function(form) { form.submit(); } });
By default, the form submission is prevented when the form is invalid, and submitted as normal when it is valid. You can also handle the submission manually (option submitHandler
).
To skip validation while still using a submit-button, add the attribte "formnovalidate" to that input:
<input type="submit" name="go" value="Submit"> <input type="submit" formnovalidate name="cancel" value="Cancel">
This used to work by adding class="cancel"
to the input, this is now deprecated.
While developing and debugging the form, you should set the debug
option to true.
That prevents form submission on both valid and invalid forms and outputs some helpful messages to window.console (available via Firebug or Firebug Lite) that help debugging
When you have everything set up and don‘t get any error messages displayed, check if your rules all accept empty elements as valid (like email or url methods).
Some issues are caused by certain form element‘s names.
The plugin can handle only one form per call.
In case you have multiple forms on a single page which you want to validate, you have to initialise them all individually:
$( "form" ).each( function() { $( this ).validate( options ); } );
You can avoid having to duplicate the plugin settings by modifying the defaults, using jQuery.validator.setDefaults to override multiple settings at once.
目标:
The ultimate goal of this plugin is to make working with forms more fun for everyone.
By improving the interaction, it is easier and less annoying for the user to fill out the form and submit it.
To achieve this, it is important that the plugin is actually deployed on websites around the world,
so a lot of focus is spent on making it easy for developers – that‘s you – to use the plugin.
The plugin can never replace serverside validation and doesn‘t intend to do so.
Having both in place gives you the necessary security for your application, as well as improved usability.
使用建议
<label for="firstname">Firstname</label> <input id="firstname" name="fname">
标签:generic tle after The fill lex however inline security
原文地址:https://www.cnblogs.com/panpanwelcome/p/10185516.html