In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the "jQuery form verification code how to write" related knowledge, editor through the actual case to show you the operation process, the method of operation is simple and fast, practical, hope that this "jQuery form verification code how to write" article can help you solve the problem.
Form validation based on jQuery
You can do some initialization configuration when using the jquery-validate.js plug-in
When initializing the jquery-validate.js object, merge some external configurations with some default configurations inside the plug-in. If there is the same configuration, the former overrides the latter (default) configuration.
/ / Constructor for validator$.validator = function (options, form) {this.settings = $.extend (true, {}, $.validator.defaults, options); this.currentForm = form; this.init ();}; format of rules
The standard format is that key is a string and value is a literal quantity of an object.
Rules: {username: {required: true, minlength: 2}}
Or it could be.
Key is a string, and value is also a specific string ("required")
Ulus: {username: "required"}
The above format will be adjusted to: {required:true} in the plug-in. You can see from the following code that it doesn't apply to usernname: "minlength". It turns it into {minlength:true}, which is obviously not appropriate.
/ / Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} normalizeRule: function (data) {if (typeof data = "string") {var transformed = {}; $.each (data.split (/\ s /), function () {transformed [this] = true;}); data = transformed } return data;}
Jquery-validate.js parses these rules and puts them into the object rules for access during verification.
Plug-in event listening processing
Adds event listeners to the specified element
$(this.currentForm) .on ("focusin.validate focusout.validate keyup.validate", ": text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search']," + "[type='tel'], [type='url'], [type='email'], [type='datetime'] [type='date'], [type='month'], "+" [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], "+" [type='radio'], [type='checkbox'], [contenteditable], [type='button'] ", delegate) / / Support: Chrome OldIE / / "select" is provided as event.target when clicking an option .on ("click.validate", "select, option, [type='radio'], [type='checkbox']", delegate)
The above listening events look strange, separated by spaces, plus namespaces. If you don't know how to use on, you can refer to the Query.on () function for details. Previously, focusin,focusout,keyup is a standard event, but I always thought that focusin and focusout were custom events, so you need to pay attention here.
Listening function processing
Function delegate (event) {/ / Set form expando on contenteditable if (! this.form & & this.hasAttribute ("contenteditable")) {this.form = $(this) .closest ("form") [0] } var validator = $.data (this.form, "validator"), eventType = "on" + event.type.replace (/ ^ validate/, ""), settings = validator.settings If (settings [eventType] & &! $(this) .is (settings.ignore)) {settings [eventType] .call (validator, this, event);}}
Settings in the plug-in places event handlers (settings [eventType] .call (validator, this, event);, that is, onfocusin,onfocusout,onkeyup,onclick,highlight,unhighlight events defined in defaults, because these events can be rewritten externally in defaults to do some custom style, which will finally re-encapsulate a form validation plug-in that suits you)
Custom event
Now take a closer look at how these custom events work in the plug-in
First take a look at a trigger () method provided by jQuery
The trigger () method triggers the specified event type of the selected element.
Format: $(selector) .trigger (event, [param1,param2, …])
Event is required. Specifies the event to be triggered by the specified element. You can make custom events (attached using the bind () function), or any standard event.
[param1,param2,...] Optional. Additional parameters passed to the event handler. Additional parameters are particularly useful for custom events.
Notice that trigger can trigger events bound by bind functions (bind is now replaced by on), that is, as long as I define some custom events in on, they can be triggered through trigger
Example-trigger
JQuery-validation demo | Bootstrap
$(".listener") .on ("customizeEvent otherEvent", ".validate, [type='text']", function () {alert ("complete some logical codes here");}) $(".validate") .trigger ("customizeEvent"); $("[type='text']") .trigger ("customizeEvent"); $("[type='text']") .trigger ("otherEvent")
In the above code, the first parameter of on has two kinds of events, separated by space (so that both events are bound to the specified event handler), the second parameter specifies some elements that can trigger this custom event (elements that satisfy selector [type='text'], validate), and the third parameter specifies the handler function to be executed when these events are triggered using trigger.
In the following execution of the event trigger, you can see from the code that I chose to trigger different events for the two elements.
Plug-in form submit snooping
The plug-in binds the submit listening event (.validate is the namespace). When we trigger the submit event through $("form"). Submit () or directly click type= "submit" (input, button can specify type= "submit"), the bound handler will be executed.
Example-bind submit
This.on ("submit.validate", function (event)
/ / Prevent submit for invalid forms or custom submit handlers if (validator.cancelSubmit) {validator.cancelSubmit = false; return handle ();} if (validator.form ()) {/ / verify the form successfully if (validator.pendingRequest) {validator.formSubmitted = true Return false;} return handle ();} else {validator.focusInvalid (); return false;}
CancelSubmit
CancelSubmit is a member property of the validator object, when the button that satisfies the selector ": submit" (the type of input,button is submit or button does not specify the type most browsers will regard button as a button of type submit) triggers the click event, it will check whether the button contains the class of "cancel" or formnovalidate= "formnovalidate" attribute, if one of them exists, then there will be no form verification and directly submit the form form (set validator.cancelSubmit=true).
Validator.form ()
Use validator.form () for form element verification, if true, determine whether validator.pendingRequest is true, if so, do not submit form, if false, execute the handle function (handle performs the processing of submitHandler ())
SubmitHandler
The plug-in can configure the submitHandler handler externally, which means that you can do some extra processing when the form form is submitted and decide whether or not to submit the form by returning true,false.
Function handle () {/ / submit form var hidden, result If (validator.settings.submitHandler) {if (validator.submitButton) {/ / Insert a hidden input as a replacement for the missing submit button hidden = $(") .attr (" name ") Validator.submitButton.name) .val ($(validator.submitButton) .val ()) .appendto (validator.currentForm) } result = validator.settings.submitHandler.call (validator, validator.currentForm, event); if (validator.submitButton) {/ / And clean up afterwards; thanks to no-block-scope, hidden can be referenced hidden.remove () } if (result! = = undefined) {return result;} return false;} return true;}
Generate an input hidden field for hidden, which is removed after the submitHandler is executed, without understanding the intention here. After executing submitHandler, a result is returned (true | false | undefined). If the custom submitHandler does not have return, the result is undefined. As a result, the result of handle () is false, and the form will not be submitted.
Rules for plug-in form validation
/ ^ [a-zA-Z0-9 / 2 / /? ^ _ `{|} ~ -] + @ [a-zA-Z0-9] (?: [a-zA-Z0-9 -] {0-61} [a-zA-Z0-9])? (?:\. [a-zA-Z0-9] (?: [a-zA-Z0-9 -] {0C.61} [a-zA-Z0-9])?) * $/
one
Url
/ ^ (?: https? | ftp):)\ /\ /) (?:\ S+ (?::\ S*)? @)? (: (?!) (? 10 | 127) (?:\.\ d {1Magazine 3}) {3}) (?! (? 169\ .254 | 192\ .168) (?:\.\ d {1pm 3}) {2}) (?! 172\. (?): 1 [6-9] | 2\ d | 3 [0-1]) ?:\.\ d {1Magne3}) {2}) (?: [1-9]\ d? | 1\ d\ d | 2 [01]\ d | 22 [0-3]) (?:\. (?: 1?\ d {1J 2} | 2 [0-4]\ d | 25 [0-5])) {2} (?:\. (?: [1-9]\ d? | 1\ d\ d | 2 [0-4]\ d | 25 [0-4])) | \ u00a1 -\ uffff0-9]-*) * [amurz\ u00a1 -\ uffff0-9] +) (?:\. (?: [Amurz\ u00a1 -\ uffff0-9]-*) * [Amurz\ u00a1 -\ uffff0-9] +) * (:\. (?: [aRaz\ u00a1 -\ uffff] {2 })).) (?::\ d {2jue 5})? (?: [/ #]\ S*)? $/ I
one
time
! / Invalid | NaN/.test (new Date (value) .toString ()
one
Phone number
/ ^ (?: -?\ d + | -?\ d {1Magne3} (?:,\ d {3}) +)? (?:\.\ d +)? $/ .test (value)
one
Figures
/ ^\ d+$/.test (value)
one
Minlength
Minlength: function (value, element, param) {
Var length = $.isArray (value)? Value.length: this.getLength (value, element)
Return this.optional (element) | | length > = param
}
This is the end of the content about "how to write the code for jQuery form validation". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.