JQuery Validata Plug-in implementation (per Monday plug-in series)

Source: Internet
Author: User

Hello everyone, the first time to write a bit of formal blog, has been readily copied a few times. In order to play lol, I wrote faster, the code I copied at the bottom, and wrote a lot of comments.

First I write jquery plug-ins, like this write (benefits have a lot, later in the talk, Haha, read the jquery source should know):

(function (root,factory,plug,undefined) {

Factory (Root.jquery,plug)

}) (Window,function ($,plug) {

/*

Write the logic here

One: The default parameter var __defaults__,

Two: Rules (can be configured according to business requirements) Var __rules__,

Three: prototype Var __prototype__,

_init: Initializing the DOM structure, nothing will,

_attachevent: The mechanism of custom events (in fact, the trigger of jquery)

_bind: The first is the binding of the event function, for each input is bound event, each loop __rules__ (is the rule), find so the value of the custom data (that is, each input required by the rule check), with if to judge, Several data properties are configured in the current input, and by Rule.call (_$field) (the meaning of this is to call the rule function, the This reference in the rule function becomes _$field), and the rule rules in input are judged. If False, then add a P tag under the parent element of input, so how do you let the user configure the contents of the P tag? <p class= ' message ' > ' + (_$field.data (key+ "-message") | | _$this.errormessage) + "</P> This means that if it is wrong, then the rule is not retrieved and the result is returned directly (because the rule returns false, so the result here is false). To stop. The P tag is added, and the parent element of input is judged according to the value of result, and a parent element plus a success or error. Finally, there is a Submit method: This method is used to determine which custom event is triggered by having no error in the class of the input parent element.

Four: $.fn[plug]

A: First determine whether the current element is from the tag, not the case, throw a wrong

II: $.extend (this,__defaults__,options,__prototype__); (.... There seems to be a classmate interview dead on this top, have time to talk about it)

Three: This._init (); This._bind (); return this;

Five: According to business needs, user-defined add rule: is to add a method as follows, you can, (next time to talk about extend bar)

$.fn[plug].extendrules = function (news) {
$.extend (__rules__,news);
}

VI: Ajax

function Login () {
var username = $ (' #username '). Val (), Password = $ (' #password '). Val ();
var data = {"uname": Username, "Upwd":p Assword};
$.ajax ({
URL: '/login ',
Type: ' POST ',
Data:data,
Success:function (data,status) {
if (status = = ' Success ') {
location.href= ' home ';
}
},
Error:function (data,status) {
if (Status = = "Error") {
location.href= ' Login '
}
}
});
}

Js:

;(function (root,factory,plug,undefined) {
Factory (Root.jquery,plug);
}) (Window,function ($,plug) {
Default parameters
var __defaults__ = {
Triggerevent: "KeyUp",
ErrorMessage: "You entered a wrong"
};
/*
require (requirement) required
Regex (regular expression) regular validation
Length Verification
MinLength the shortest length
The longest length of maxlength
Between the length between the two
Equalto and XXX are the same
GreaterThan Greater than
LessThan less than
Middle the numbers between the two
Integer integers
Number must be numeric
Email email address
Mobile phone number
Phone number
URI valid Uniform Resource Identifier
CardId ID Number
BankID Bank card number
.... Other rules (according to business rules)
*/
var __rules__ = {
Require:function () {
Return This.val ()! = "";
},//(required) required fields
Regex:function () {
return new RegExp (This.data ("regex")). Test (This.val ());
},//(regular expression) regular validation
Length:function () {
Return This.val (). Length = = Number (This.data ("Length"));
},//Length verification
Minlength:function () {
Return This.val (). Length >= number (This.data ("minlength"));
},//Shortest length
Maxlength:function () {
Return This.val (). Length <= number (This.data ("maxlength"));
},//Longest length
Between:function () {
var length = This.val (). length;
var between = This.data ("between"). Split ("-");
Return length >= number (between[0]) && length <= number (between[1]);
},//length between the two
Equalto:function () {
if ($ (This.data ("Equalto")). val () = = = This.val ()) {
$ (This.data ("Equalto")). Parent (". Mf-line"). Removeclass (' Error '). addclass (' success '). Next ("P"). Remove ();
return true;
}
return false;
},//and XXX same
Greaterthan:function () {
return This.val () > Number (This.data ("GreaterThan"));
},//greater than
Lessthan:function () {
Return This.val () < number (This.data ("LessThan"));
},//less than
Middle:function () {
var length = This.val ();
var middle = this.data ("Middle"). Split ("-");
Return length >= number (middle[0]) && length <= number (middle[1]);
},//number between the two
Integer:function () {
Return/^\-? [0-9]*[1-9][0-9]*$/.test (This.val ());
},//Integer
Number:function () {
Return!isnan (Number (This.val ()));
},//Must be a number
Email:function () {
Return/^\w+ ((-\w+) | ( \.\w+)) *\@[a-za-z0-9]+ ((\.| -) [a-za-z0-9]+] *\. [A-za-z0-9]+$/.test (This.val ());
},//email address
Mobile:function () {
Return/^1\d{10}$/.test (This.val ());
},//Phone number
Phone:function () {
Return/^\d{4}\-\d{8}$/.test (This.val ());
},//mobile number
Uri:function () {
Return/((^https:(?: \ /\/)?) (?: [-;:&=\+\$,\w][email protected])? [a-za-z0-9.-]+| (?: www.| [-;:&=\+\$,\w] [Email protected]) [a-za-z0-9.-]+] (?: \ /[\+~%\/.\w-_]*)??? (?: [-\+=&;%@.\w_]*) #? (?: [\w]*))?) $/g.test (This.val ());
},//valid Uniform Resource Identifier
Amount:function () {//Amount
if (!this.val ()) return true;
Return/^ ([1-9][\d]{0,}|0) (\.[ \d]{1,2})? $/.test (This.val ());
}
};
var __prototype__ = {
Initializing the DOM structure
_init:function () {
this. $fields = This.find (". Mf-line. mf-txt:visible"); Select the visible input (filter out Display:none)
},
Trigger mechanism for custom events
_attachevent:function (event, args) {
This.trigger (event, args);
},
Event
_bind:function () {
var _$this = this;
Event feature Bindings
this. $fields. On (this.triggerevent, function () {
var _$field = $ (this); Forms that need to be validated
var $group = _$field.parents (". Mf-line"); Get the div for input
var result = true;
$group. Next ("P"). Remove ();
$.each (__rules__,function (key,rule) {
if (_$field.data (key)) {
result = Rule.call (_$field);
(!result) && $group. After ("<p class= ' message ' >" + (_$field.data (key+ "-message") | | _$this.errormessage) + "</p>");
return result;
}
})
$group. Removeclass (' ERROR success '). AddClass (result? ') Success ': ' Error ');
})
This.on ("Submit", function () {
var $groups = _$this. $fields. Trigger (_$this.triggerevent). Parents (". Mf-line");
if ($groups. Filter (". Error"). Length > 0) {
_$this._attachevent ("Error", {});
}else{
_$this._attachevent ("Success", {});
}
return false;
})
}
}
$.fn[plug] = function (options) {
Determine if this is a form label
if (!this.is ("form")) {
throw new Error ("The Trgger is not a form tag");
}
$.fn.extend (this,__defaults__,options,__prototype__);
This._init ();
This._bind ();
return this;
}
$.fn[plug].extendrules = function (news) {
$.extend (__rules__,news);
}
}, "validator");

This is the JS that calls the plugin

$ (function () {
$.fn.validator.extendrules ({
Cardid:function () {
return/(^\d{15}$) | (^\d{18}$) | (^\d{17} (\d| x|x)/.test (This.val ());
}
})
$ (". Member-forms"). Validator ({
Triggerevent: "Blur"
})
. On ("Error", Function (event, $errFiles) {
return false;
})
. On ("Success", function (event) {
This.submit ();
return false;
});
});

Html:

<! DOCTYPE html>
<meta charset= "UTF-8"/>
<title>validata</title>
<link rel= "stylesheet" type= "Text/css" href= "Css/validata.css"/>
<body>
<div class= "wrapper Mt30" >
<form action= "# #" class= "member-forms" method= "Get" >
<div class= "mf-head rel TC" >
<span class= "F24" > User login </span>
</div>
<div class= "Mf-line" >
<span class= "Mf-name" > Account:</span>
<input type= "text" class= "Mf-txt" id= "username" placeholder= "Please enter your username/Phone number"
Data-require= "true"
Data-require-message= "User name must be filled in"
data-regex= "^\w+$"
Data-regex-message= "The user should be made up of alphanumeric underscores"
Data-between= "6-12"
data-between-message= "User name length must be between 6-12-bit characters"
/>
</div>
<div class= "Mf-line" >
<span class= "Mf-name" > Password:</span>
<input type= "Password" class= "mf-txt" id= "password" placeholder= "Please enter password"
Data-require= "true"
data-require-message= "Password must be filled in"
data-regex= "^[a-za-z0-9]+$"
Data-regex-message= "The password should be made up of an alphabetical array"
Data-minlength= "8"
data-minlength-message= "Minimum password length 8 bits"
Data-maxlength= "12"
data-maxlength-message= "Password length up to 12 bits"
/>
</div>
<input type= "Submit" class= "mf-btn mt30" id= "loginbtn"/>
</form>
</div>
<script type= "Text/javascript" src= ". /jquery-2.2.4.js "></script>
<script type= "Text/javascript" src= "Plug_in/validata.js" ></script>
<script type= "Text/javascript" src= "Js/index.js" ></script>
</body>

Css:

body,html{
width:100%;
height:100%;
font-family: "Microsoft Yahei";
}
*{
margin:0;
padding:0;
}
. tc{
Text-align:center;
}
. f24{
font-size:24px;
}
. rel{
position:relative;
}
. wrapper{
max-width:1186px;
}
. mt30{
margin-top:30px;
}
. member-forms{

max-width:400px;
margin:20px Auto;
padding:0 10px;
Background-color: #fff;
}
. member-forms. mf-line{
margin-top:30px;
border:1px solid #ddd;
line-height:52px;
Position:r elative;
padding-left:110px;
Border-radius:4px;
}
. member-forms. mf-line.error{
border:1px solid #a94442;
}
. member-forms. mf-line.success{
border:1px solid #3c763d;
}
. member-forms. Mf-line. mf-name{
Position:absolute;
left:0;
right:0;
Text-align:center;
Width : 110px;
}
. member-forms. Mf-line. mf-txt{
Display:block;
height:50px;
width:96%;
border:0px;
Paddi Ng:0 2%;
}
. member-forms. message{
width:400px;
font-size:12px;
Color:red;
}
. member-forms. mf-btn{
height:52px;
line-height:52px;
Color: #fff;
Background-color: #5ba0e5 ;
width:100%;
Text-align:center;
Cursor:pointer;
font-size:18px;
border:0px;
}

JQuery Validata Plug-in implementation (per Monday plug-in series)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.