jquery Form Validation Validator plug-in usage

Source: Internet
Author: User
Tags abs button type return tag setinterval tagname trim jquery form validation


This period of time to work more idle, the total feeling can not let their technology deserted, so again the old line, do a small demo to.

This time I made a JS version of the form verification plug-in, the overall principle of reference to the jquery validate, but in some small areas still have their own innovation.

The main features of this plugin are the following.

1. Validation Rule customization
You can configure the form items that need to be validated by yourself, and you can make your own decisions to maximize the flexibility of the plug-in when validating the pass or error.

2. Various verification methods
Plug-ins provide a rich range of authentication types, such as null, length, size, equality, Remote authentication, data type validation, and so on.

3, the prompt mechanism is sound
When you work on a form, you can configure it to determine when the validation occurs, such as when the form is submitted, when validation is done, when the focus is lost or when it is received, and when it is clicked.

4. Object-oriented design
This plug-in code uses object-oriented design, each function method Division of labor detail, mutual interference, minimize redundancy.

Due to the time, it is possible that the plugin has a lot of places where there is a shortage of time, and then will be a good rest.


Instance




<! DOCTYPE html>


<html>


<head>


<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>





<link rel= "stylesheet" href= ". /external/bootstrap/css/bootstrap.min.css "/>


<style>


. error,span.valid{font-size:12px;vertical-align:middle;padding-left:5px;}


. Error{color: #b94a48;}


. Valid{color: #468847;}


Input.error,textarea.error,select.error{border-color: #b94a48;}


Input.valid,textarea.valid,select.valid{border-color: #468847;}


. form-horizontal. control-group{margin-bottom:0;


</style>


</head>


<body>


<div class= "Row-fluid span10" >


<form id= "form" class= "Form-horizontal" action= "javascript:void (0);" >


<fieldset>


<legend>DEMO:</legend>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "username" class= "add-on" > Name <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "username" id= "username" placeholder= "Xiechengxiong already exist"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "Password1" class= "add-on" > Password <span class= "Icon-asterisk" ></span></label>


<input type= "Password" name= "Password1" id= "Password1"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "Password2" class= "add-on" > re-transmission password <span class= "Icon-asterisk" ></span></label>


<input type= "Password" name= "Password2" id= "Password2"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "Email" class= "add-on" > Mailbox <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "email" id= "email"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "url" class= "add-on" > Web site <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "url" id= "url"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "Date" class= "add-on" > Date <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "date" id= "date"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "Dateiso" class= "add-on" > Date (ISO) <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "Dateiso" id= "Dateiso"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "number" class= "add-on" > Digital <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "number" id= "number"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "digits" class= "add-on" > Integer <span class= "Icon-asterisk" ></span></label>


<input type= "text" name= "digits" id= "digits"/>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "textarea" class= "add-on" > Text field <span class= "Icon-asterisk" ></span></label>


<textarea name= "textarea" id= "textarea" ></textarea>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label class= "Add-on" > Radio <span class= "Icon-asterisk" ></span></label>


<label class= "Radio inline" ><input type= "Radio" name= "Radio" id= "Radio1"/>1</label>


<label class= "Radio inline" ><input type= "Radio" name= "Radio" id= "Radio2"/>2</label>


<label class= "Radio inline" ><input type= "Radio" name= "Radio" id= "Radio3"/>3</label>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label class= "Add-on" > Multiple selection <span class= "Icon-asterisk" ></span></label>


<label class= "checkbox inline" ><input type= "checkbox" name= "checkbox" id= "CheckBox1"/>1</label>


<label class= "checkbox inline" ><input type= "checkbox" name= "checkbox" id= "CheckBox2"/>2</label>


<label class= "checkbox inline" ><input type= "checkbox" name= "checkbox" id= "Checkbox3"/>3</label>


</div>


</div>


<div class= "Control-group" >


<div class= "Input-prepend" >


<label for= "Select" class= "add-on" > Drop-down list (multiple selection) <span class= "Icon-asterisk" ></span></label>


<select name= "Select" id= "select" multiple= "multiple" >


<option>1</option>


<option>2</option>


<option>3</option>


</select>


</div>


</div>


<div class= "Btn-group" >


<button type= "Submit" class= "BTN btn-primary" > Submit </button>


<button type= "reset" class= "BTN" > Reset </button>


</div>


</fieldset>


</form>


</div>


<script >


/*


*project:blog Poject


*version:2.0


*create:2013-3-10


*update:2013-7-3 11:00


*update:2013-9-24 18:27


*AUTHOR:F2E Xiechengxiong


*/


(Function (win, doc) {


var X = win[' x '] | | {};


X = {


$: function (ID) {


return Doc.getelementbyid (ID);


},


Accordion:function (obj, step, num, type) {


if (Obj.timer) {


Clearinterval (Obj.timer);


}


Obj.timer = setinterval (function () {


X.accordion (obj, step, num, type);


}, 10);


var curwidth = Type = = ' width '? Obj.clientWidth:obj.clientHeight;


if (curwidth = = num) {


Clearinterval (Obj.timer);


Obj.timer = null;


} else {


Obj.style[type] = curwidth + step + ' px ';


}


},


Addclass:function (node, className) {


if (!this.hasclass (node, className)) {


Node.classname = node.classname + ' + className;


}


},


Addcss:function (URL, fn) {


var link = doc.createelement (' link ');


Link.href = URL;


Link.type = ' text/css ';


Link.rel = ' stylesheet ';


This.onload (link, FN);


Doc.getelementsbytagname (' head ') [0].appendchild (link);


},


Addevent:function (node, type, fn) {


if (Node.addeventlistener) {


Node.addeventlistener (Type, FN, false);


else if (node.attachevent) {


Node.attachevent (' on ' + type, fn);


} else {


node[' on ' + type] = fn;


}


},


Addscript:function (URL, fn) {


var script = doc.createelement (' script ');


Script.type = ' Text/javascript ';


This.onload (script, FN);


Doc.getelementsbytagname (' head ') [0].appendchild (script);


script.src = URL;


return script;


},


Ajax:function (opts) {


var dataType = Opts.dataType.toLocaleLowerCase ();


Opts.data = decodeURIComponent (typeof opts.data = = ' undefined '? ': typeof opts.data = = ' object '? This.obj2str (opts.data): Opts.data);


if (DataType = = ' Jsonp ') {


var fnname = ' Jsonp_ ' + Math.floor (math.random () * 10E10) + ' _ ' + new Date (). GetTime ();


Opts.url = Opts.url + '? callback= ' + FnName + ' & ' + Opts.data + ' & ' + ' r= ' + new Date (). GetTime ();


var script = This.addscript (opts.url, NULL);


Win[fnname] = function (data) {


OPTS.SUCFN && OPTS.SUCFN (data);


Doc.getelementsbytagname (' head ') [0].removechild (script);


};


} else {


var req = win. XMLHttpRequest? New XMLHttpRequest (): New ActiveXObject (' microsoft.xmlhttp ');


if (Opts.type && opts.type.toLocaleLowerCase () = = ' Post ') {


Req.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded;charset=utf-8 ');


else if (opts.data!== ') {


Opts.url = Opts.url + '? ' + opts.data;


}


Req.open (Opts.type, Opts.url, true);


Req.send (Opts.data);


Req.onreadystatechange = function () {


if (req.readystate = = 4) {


if (Req.status = = 200) {


OPTS.SUCFN && OPTS.SUCFN (dataType = = ' json '? X.parsejson (Req.responsetext): Req.responsetext);


} else {


OPTS.FAILFN && OPTS.FAILFN (req.status);


}


}


};


}


},


Append:function (node, parent) {


if (typeof node = = ' object ') {


Parent.appendchild (node);


} else {


var fragment = Doc.createdocumentfragment ();


fragment.innerhtml = node;


Parent.appendchild (fragment);


}


},


Attr:function (element, Attrname, Attrval) {


if (arguments.length = = 2 && typeof attrname = = ' String ') {


Return Element.getattribute (attrname);


} else {


var attr = {};


if (typeof attrname = = = ' String ') {


Attr[attrname] = Attrval;


} else {


attr = Attrname;


}


for (var n in attr) {


Element.setattribute (n, Attr[n]);


}


}


return element;


},


/**


* Deep Clone object or array, block JS in the reference to pass


* @param obj object or array to be cloned


* @returns {*} returns a cloned object or array


*/


Clone:function (obj) {


var newObj;


if (typeof obj = = = ' object ') {


if (Object.prototype.toString.call (obj) = = ' [Object Array] ') {


NEWOBJ = [];


var i = obj.length;


while (i--) {


Newobj[i] = T.clone (Obj[i]);


}


return NEWOBJ;


} else {


NEWOBJ = {};


for (var j in obj) {


NEWOBJ[J] = T.clone (Obj[j]);


}


}


} else {


return obj;


}


return NEWOBJ;


},


Css:function CSS (node, attr) {


if (attr!= ' opacity ') {


return parseint (Node.currentstyle node.currentstyle[attr]: Doc.defaultView.getComputedStyle (node, false) [attr]);


} else {


return Math.Round parsefloat (Node.currentstyle node.currentstyle[attr]: Doc.defaultView.getComputedStyle ( node, false) [attr]);


}


},


Delclass:function (node, className) {


if (This.hasclass (node, className)) {


The var cls = Node.classname;


if (ClassName = = CLS) {


CLS = ';


} else {


CLS = Cls.replace (' + className, '). Replace (ClassName + ', ');


}


Node.classname = CLS;


}


},


Delevent:function (node, type, fn) {


if (Node.removeeventlistener) {


Node.removeeventlistener (Type, FN, false);


else if (node.detachevent) {


Node.detachevent ("On" + Type, fn);


} else {


Node["on" + type] = NULL;


}


},


Dir:function (data) {


try {


Console.dir (data);


catch (ex) {


}


},


Each:function (FN) {


for (var i = 0; i < this.length; i++) {


if (FN && Fn.call (this[i], i) = = False) {


Break


}


}


},


Extend:function (target, options) {


for (var name in options) {


var copy = Options[name];


if (target = = copy) {


Continue


}


if (copy!== undefined) {


Target[name] = copy;


}


}


return target;


},


Fadein:function (obj) {


if (Obj.timer) {


Clearinterval (Obj.timer);


}


Obj.timer = setinterval (function () {


X.fadein (obj);


}, 100);


if (!win[' xcxfadeinopacity ']) {


win[' xcxfadeinopacity '] = 0;


Obj.style.display = ';


}


win[' xcxfadeinopacity '] + + 0.1;


obj.style.opacity = win[' xcxfadeinopacity '] + ';


if (win[' xcxfadeinopacity '] >= 1) {


win[' xcxfadeinopacity '] = 0;


Clearinterval (Obj.timer);


}


},


Fadeout:function (obj) {


if (Obj.timer) {


Clearinterval (Obj.timer);


}


Obj.timer = setinterval (function () {


X.fadeout (obj);


}, 100);


if (!win[' xcxfadeoutopacity ']) {


win[' xcxfadeoutopacity '] = 1;


}


win[' xcxfadeoutopacity ']-= 0.1;


obj.style.opacity = win[' xcxfadeoutopacity '] + ';


if (win[' xcxfadeoutopacity '] <= 0) {


Obj.style.display = ' None ';


win[' xcxfadeoutopacity '] = 1;


Clearinterval (Obj.timer);


}


},


Filter:function (list, fn) {


var reList = [];


This.each.call (list, function () {


if (Fn.call (this)) {


Relist.push (this);


}


});


Relist.each = function (fn) {


X.each.call (ReList, FN);


};


return reList;


},


Getbrowser:function () {


var bs = {};


var u = win.navigator.userAgent.toLocaleLowerCase (),


Sougou =/se 2.x METASR 1.0/,


Qqbrowser =/(Qqbrowser)/([D.] +)/,


MSIE =/(MSIE) ([D.] +)/,


Chrome =/(chrome)/([D.] +)/,


Firefox =/(Firefox)/([D.] +)/,


Safari =/(Safari)/([D.] +)/,


Opera =/(opera)/([D.] +)/,


b = U.match (Sougou) | | U.match (qqbrowser) | | U.match (MSIE) | | U.match (chrome) | | U.match (Firefox) | | U.match (Safari) | | U.match (opera) | | [0, 0, 0];


if (b[1] = = ' Opera ' | | b[1] = = ' Safari ') {


B[2] = U.match (/version)/([D.] +)/) [2];


}


if (U.match (Sougou)) {


b = [];


B[1] = ' Sougo ';


B[2] = ' msie7.0 ';


}


BS[B[1]] = b[2];


bs[' name '] = b[1];


bs[' version '] = b[2];


return BS;


},


Getbyattr:function (Attrname, Attrval, parent) {


Parent = Parent | | Doc.body;


var list = [];


var elements = parent.getelementsbytagname (' * ');


for (var i = 0; i < elements.length; i++) {


var element = Elements[i];


var reg = new RegExp (Attrval.replace (/,/g, ' | '), ' G ');


if (Reg.test (Element.getattribute (attrname)) {


List.push (Element);


}


}


List.each = function (fn) {


X.each.call (list, FN);


};


return list;


},


Getbyclass:function (ClassName, parent) {


var node = parent | | Doc


var list = [];


if (node.getelementsbyclassname) {


List = Node.getelementsbyclassname (className);


} else {


var nodes = node.getelementsbytagname (' * ');


for (var i = 0; i < nodes.length; i++) {


if (This.hasclass (Nodes[i], className)) {


List.push (Nodes[i]);


}


}


}


List.each = function (fn) {


X.each.call (list, FN);


};


return list;


},


Getbytag:function (TagName, parent) {


Parent = Parent | | Doc.body;


var list = [];


var tags = tagname.split (', ');


for (var i = 0, len = tags.length i < len; i++) {


var nl = parent.getelementsbytagname (tags[i]);


for (var j = 0, Jlen = nl.length J < Jlen; J + +) {


List.push (Nl[j]);


}


}


List.each = function (fn) {


X.each.call (list, FN);


};


return list;


},


Geteventxy:function (E, isend) {


E = e | | Win.event;


if (! (' Ontouchstart ' in Win ') {


return [e[' Pagex '], e[' Pagey ']];


else if (isend) {


return [e.changedtouches[0][' Pagex '], e.changedtouches[0][' Pagey ']];


}


return [e.touches[0][' Pagex '], e.touches[0][' Pagey ']];


},


Getoffset:function (obj) {


var arr = (function (o) {


var L = 0, t = 0;


while (o!== null && o!== doc.body) {


L + + O.offsetleft;


T + + o.offsettop;


o = o.offsetparent;


}


return [L, T];


}) (obj);


Arr.push (Obj.offsetwidth);


Arr.push (Obj.offsetheight);


return arr;


},


Getquerystringargs:function () {


var qs = (Win.location.search.length > 0 win.location.search.substring (1): ");


var args = {};


var items = qs.length? Qs.split (' & '): [];


var len = items.length;


for (var i = 0; i < len; i++) {


var item = items[i].split (' = ');


var name = decodeURIComponent (item[0]);


var value = decodeuricomponent (item[1]);


if (name.length) {


Args[name] = value;


}


}


return args;


},


Hasclass:function (node, className) {


var names = Node.className.split (/s+/);


for (var i = 0; i < names.length; i++) {


if (names[i] = = ClassName) {


return true;


}


}


return false;


},


Isarray:function (o) {


return Object.prototype.toString.call (o) = = ' [Object Array] ';


},


Isleapyear:function (y) {


var flag = false;


if ((y% 400 = 0) | | (y%!== 0) && (y% 4 = 0)) {


Flag = true;


}


return flag;


},


Log:function (data) {


try {


Console.log (data);


catch (ex) {


}


},


Obj2str:function (obj) {


var str = [];


Switch (TRUE) {


Case typeof obj = = ' undefined ':


str = ';


Break


Case typeof obj = = ' String ':


str = ' "' + obj.replace (/([" \])/g, ' \$1 '). Replace (/(n)/g, ' \ n '). Replace (/(R)/g, ' \ R '). Replace (/(t)/g, ' t ') + ' ";


Break


Case typeof obj = = ' object ':


if (!this.isarray (obj)) {


for (var i in obj) {


Str.push (' "' + i + '": ' + this.obj2str (Obj[i]));


}


if (!! Doc.all &&!/^n?functions*tostring () s*{n?s*[native code]n?s*}n?s*$/.test (obj.tostring)) {


Str.push (' toString: ' + obj.toString.toString ());


}


str = ' {' + str.join () + '} ';


} else {


for (var j = 0; J < Obj.length; J + +) {


Str.push (This.obj2str (obj[j));


}


str = ' [' + str.join () + '] ';


}


Break


Default


str = obj.tostring (). Replace (/":/g, '": "");


Break


}


return str;


},


Onload:function (obj, fn) {


Obj.onload = function () {


FN ();


};


if (This.getbrowser (). Name = = = ' Msie ') {


var t = win.setinterval (function () {


if (obj.readystate = = ' Loaded ' | | | obj.readystate = = ' complete ') {


Win.clearinterval (t);


FN ();


}


}, 10);


}


},


Parsejson:function (data) {


if (!data | | typeof data!== "string") {


return null;


}


data = This.trim (data);


if (win. JSON && win. Json.parse) {


Return win. Json.parse (data);


}


Return (The New Function ("return" + Data)) ();


},


Preventdefault:function (e) {


E = e | | Win.event;


if (E.preventdefault) {


E.preventdefault ();


} else {


E.returnvalue = false;


}


},


Stoppropagation:function (e) {


if (e.stoppropagation) {


E.stoppropagation ();


} else {


E.cancelbubble = true;


}


},


Swipe:function (obj, SFn, MFn, eFn) {


var canmove, XY;


This.addevent (obj, ' Touchstart ', function (e) {


Canmove = 0;


XY = X.geteventxy (e);


SFn && sFn (E, xy[0], xy[1]);


});


This.addevent (obj, ' touchmove ', function (e) {


var mxy = X.geteventxy (e);


if (Canmove = = 0) {


if (Math.Abs (mxy[0]-xy[0]) > Math.Abs (mxy[1]-xy[1)) {


Canmove = 1;


} else {


Canmove = 2;


Return


}


}


var result = MFn && mFn (E, xy[0], mxy[0]);


if (!result) {


E.preventdefault ();


E.stoppropagation ();


}


});

This.addevent (obj, ' touchend ', function (e) {


var exy = X.geteventxy (E, ' true ');


if (Canmove!== 2) {


EFn && eFn (E, xy[0], exy[0]);


Canmove = 2;


}


});


},


Touch:function (obj, fn) {


var duration = 0, fixdistance = ten, time, XY;


This.addevent (obj, ' Touchstart ', function (e) {


Time = new Date (). valueof ();


XY = X.geteventxy (e);


});


This.addevent (obj, ' touchend ', function (e) {


var result = true;


var endtime = new Date (). valueof ();


var ENDXY = X.geteventxy (E, true);


if (Endtime-time > Duration && math.abs (endxy[0)-xy[0]) < fixdistance && Math.Abs (endxy[1)-xy[ 1] < fixdistance) {


result = FN && fn (e);


}


if (!result) {


E.preventdefault ();


E.stoppropagation ();


}


});


},


Trim:function (text) {


return text = null? ': Text.replace (^s*) | ( s*$)/g, "");


}


};


Array.prototype.distinct = function () {


var sameobj = function (A, b) {


var tag = true;


if (!a | |!b) {


return false;


}


for (Var x in a) {


if (!b[x]) {


return false;


}


if (typeof (a[x]) = = = ' object ') {


Tag = Sameobj (A[x], b[x]);


} else {


if (A[x]!== b[x]) {


return false;


}


}


}


return tag;


};


var newArr = [], obj = {};


for (var i = 0, len = this.length i < len; i++) {


if (!sameobj (obj[typeof (this[i) + this[i]], this[i)) {


Newarr.push (This[i]);


Obj[typeof (This[i]) + this[i]] = this[i];


}


}


return NEWARR;


};


Win. x = x;


}) (window, document);


</script>


<script src= ". /src/js/xcx.validator.js "></script>


<script>


var valid = new Validator ({


ID: ' Form ',


Infoelement: ' Span ',


Errorclass: ' Error ',


Validclass: ' Valid ',


Rules: {


Username: {required:true,minlength:5,maxlength:20,remote: {}},


Password1: {required:true,rangelength: [6, 16]},


Password2: {required:true,rangelength: [6, 16],equalto: ' Password1 '},


Email: {Required:true,email:true},


URL: {required:true,url:true},


Date: {required:true,date:true},


Dateiso: {required:true,dateiso:true},


Number: {Required:true,number:true},


Digits: {required:true,digits:true},


TextArea: {required:true},


Radio: {required:true},


CheckBox: {required:true},


Select: {required:true}


},


Submithandler:function (form) {


Alert (' Verify success! ');


}


});


</script>


</body>


</html>

Validator.js file Everyone Baidu Download bar, here is not provided is a jquery plugin

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.