jquery.validator.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  1. /*! nice-validator 1.0.10
  2. * (c) 2012-2017 Jony Zhang <niceue@live.com>, MIT Licensed
  3. * https://github.com/niceue/nice-validator
  4. */
  5. ;(function(factory) {
  6. typeof module === "object" && module.exports ? module.exports = factory( require( "jquery" ) ) :
  7. typeof define === 'function' && define.amd ? define(['jquery'], factory) :
  8. factory(jQuery);
  9. }(function($, undefined) {
  10. "use strict";
  11. var NS = 'validator',
  12. CLS_NS = '.' + NS,
  13. CLS_NS_RULE = '.rule',
  14. CLS_NS_FIELD = '.field',
  15. CLS_NS_FORM = '.form',
  16. CLS_WRAPPER = 'nice-' + NS,
  17. CLS_MSG_BOX = 'msg-box',
  18. ARIA_REQUIRED = 'aria-required',
  19. ARIA_INVALID = 'aria-invalid',
  20. DATA_RULE = 'data-rule',
  21. DATA_MSG = 'data-msg',
  22. DATA_TIP = 'data-tip',
  23. DATA_OK = 'data-ok',
  24. DATA_TIMELY = 'data-timely',
  25. DATA_TARGET = 'data-target',
  26. DATA_DISPLAY = 'data-display',
  27. DATA_MUST = 'data-must',
  28. NOVALIDATE = 'novalidate',
  29. INPUT_SELECTOR = ':verifiable',
  30. rRules = /(&)?(!)?\b(\w+)(?:\[\s*(.*?\]?)\s*\]|\(\s*(.*?\)?)\s*\))?\s*(;|\|)?/g,
  31. rRule = /(\w+)(?:\[\s*(.*?\]?)\s*\]|\(\s*(.*?\)?)\s*\))?/,
  32. rDisplay = /(?:([^:;\(\[]*):)?(.*)/,
  33. rDoubleBytes = /[^\x00-\xff]/g,
  34. rPos = /top|right|bottom|left/,
  35. rAjaxType = /(?:(cors|jsonp):)?(?:(post|get):)?(.+)/i,
  36. rUnsafe = /[<>'"`\\]|&#x?\d+[A-F]?;?|%3[A-F]/gmi,
  37. noop = $.noop,
  38. proxy = $.proxy,
  39. trim = $.trim,
  40. isFunction = $.isFunction,
  41. isString = function(s) {
  42. return typeof s === 'string';
  43. },
  44. isObject = function(o) {
  45. return o && Object.prototype.toString.call(o) === '[object Object]';
  46. },
  47. isIE = document.documentMode || +(navigator.userAgent.match(/MSIE (\d+)/) && RegExp.$1),
  48. attr = function(el, key, value) {
  49. if (!el || !el.tagName) return null;
  50. if (value !== undefined) {
  51. if (value === null) el.removeAttribute(key);
  52. else el.setAttribute(key, '' + value);
  53. } else {
  54. return el.getAttribute(key);
  55. }
  56. },
  57. novalidateonce,
  58. preinitialized = {},
  59. defaults = {
  60. debug: 0,
  61. theme: 'default',
  62. ignore: '',
  63. focusInvalid: true,
  64. focusCleanup: false,
  65. stopOnError: false,
  66. beforeSubmit: null,
  67. valid: null,
  68. invalid: null,
  69. validation: null,
  70. formClass: 'n-default',
  71. validClass: 'n-valid',
  72. invalidClass: 'n-invalid',
  73. bindClassTo: null
  74. },
  75. fieldDefaults = {
  76. timely: 1,
  77. display: null,
  78. target: null,
  79. ignoreBlank: false,
  80. showOk: true,
  81. // Translate ajax response to validation result
  82. dataFilter: function (data) {
  83. if ( isString(data) || ( isObject(data) && ('error' in data || 'ok' in data) ) ) {
  84. return data;
  85. }
  86. },
  87. msgMaker: function(opt) {
  88. var html;
  89. html = '<span role="alert" class="msg-wrap n-'+ opt.type + '">' + opt.arrow;
  90. if (opt.result) {
  91. $.each(opt.result, function(i, obj){
  92. html += '<span class="n-'+ obj.type +'">' + opt.icon + '<span class="n-msg">' + obj.msg + '</span></span>';
  93. });
  94. } else {
  95. html += opt.icon + '<span class="n-msg">' + opt.msg + '</span>';
  96. }
  97. html += '</span>';
  98. return html;
  99. },
  100. msgWrapper: 'span',
  101. msgArrow: '',
  102. msgIcon: '<span class="n-icon"></span>',
  103. msgClass: 'n-right',
  104. msgStyle: '',
  105. msgShow: null,
  106. msgHide: null
  107. },
  108. themes = {};
  109. /** jQuery Plugin
  110. * @param {Object} options
  111. debug {Boolean} 0 Whether to enable debug mode
  112. timely {Number} 1 Whether to enable timely validation
  113. theme {String} 'default' Theme name
  114. stopOnError {Boolean} false Whether to stop validate when found an error input
  115. focusCleanup {Boolean} false Whether to clean up the field message when focus the field
  116. focusInvalid {Boolean} true Whether to focus the field that is invalid
  117. ignoreBlank {Boolean} false When the field has no value, whether to ignore validation
  118. ignore {jqSelector} '' Ignored fields (Using jQuery selector)
  119. beforeSubmit {Function} Do something before submit form
  120. dataFilter {Function} Convert ajax results
  121. valid {Function} Triggered when the form is valid
  122. invalid {Function} Triggered when the form is invalid
  123. validClass {String} 'n-valid' Add this class name to a valid field
  124. invalidClass {String} 'n-invalid' Add this class name to a invalid field
  125. bindClassTo {jqSelector} ':verifiable' Which element should the className binding to
  126. display {Function} Callback function to get dynamic display
  127. target {Function} Callback function to get dynamic target
  128. msgShow {Function} Trigger this callback when show message
  129. msgHide {Function} Trigger this callback when hide message
  130. msgWrapper {String} 'span' Message wrapper tag name
  131. msgMaker {Function} Callback function to make message HTML
  132. msgArrow {String} Message arrow template
  133. msgIcon {String} Message icon template
  134. msgStyle {String} Custom message css style
  135. msgClass {String} Additional added to the message class names
  136. formClass {String} Additional added to the form class names
  137. messages {Object} Custom messages for the current instance
  138. rules {Object} Custom rules for the current instance
  139. fields {Object} Field validation configuration
  140. {String} key name|#id
  141. {String|Object} value Rule string or an object which can pass more arguments
  142. fields[key][rule] {String} Rule string
  143. fields[key][display] {String|Function}
  144. fields[key][tip] {String} Custom tip message
  145. fields[key][ok] {String} Custom success message
  146. fields[key][msg] {Object} Custom error message
  147. fields[key][msgStyle] {String} Custom message style
  148. fields[key][msgClass] {String} A className which added to message placeholder element
  149. fields[key][msgWrapper] {String} Tag name of the message placeholder element
  150. fields[key][msgMaker] {Function} A function to custom message HTML
  151. fields[key][dataFilter] {Function} A function to convert ajax results
  152. fields[key][valid] {Function} A function triggered when field is valid
  153. fields[key][invalid] {Function} A function triggered when field is invalid
  154. fields[key][must] {Boolean} If set true, we always check the field even has remote checking
  155. fields[key][timely] {Boolean} Whether to enable timely validation
  156. fields[key][target] {jqSelector} Define placement of a message
  157. */
  158. $.fn.validator = function(options) {
  159. var that = this,
  160. args = arguments;
  161. if (that.is(INPUT_SELECTOR)) return that;
  162. if (!that.is('form')) that = this.find('form');
  163. if (!that.length) that = this;
  164. that.each(function() {
  165. var instance = $(this).data(NS);
  166. if (instance) {
  167. if ( isString(options) ) {
  168. if ( options.charAt(0) === '_' ) return;
  169. instance[options].apply(instance, [].slice.call(args, 1));
  170. }
  171. else if (options) {
  172. instance._reset(true);
  173. instance._init(this, options);
  174. }
  175. } else {
  176. new Validator(this, options);
  177. }
  178. });
  179. return this;
  180. };
  181. // Validate a field, or an area
  182. $.fn.isValid = function(callback, hideMsg) {
  183. var me = _getInstance(this[0]),
  184. hasCallback = isFunction(callback),
  185. ret, opt;
  186. if (!me) return true;
  187. if (!hasCallback && hideMsg === undefined) hideMsg = callback;
  188. me.checkOnly = !!hideMsg;
  189. opt = me.options;
  190. ret = me._multiValidate(
  191. this.is(INPUT_SELECTOR) ? this : this.find(INPUT_SELECTOR),
  192. function(isValid){
  193. if (!isValid && opt.focusInvalid && !me.checkOnly) {
  194. // navigate to the error element
  195. me.$el.find('[' + ARIA_INVALID + ']:first').focus();
  196. }
  197. if (hasCallback) {
  198. if (callback.length) {
  199. callback(isValid);
  200. } else if (isValid) {
  201. callback();
  202. }
  203. }
  204. me.checkOnly = false;
  205. }
  206. );
  207. // If you pass a callback, we maintain the jQuery object chain
  208. return hasCallback ? this : ret;
  209. };
  210. $.extend($.expr.pseudos || $.expr[':'], {
  211. // A faster selector than ":input:not(:submit,:button,:reset,:image,:disabled,[contenteditable])"
  212. verifiable: function(elem) {
  213. var name = elem.nodeName.toLowerCase();
  214. return ( name === 'input' && !({submit: 1, button: 1, reset: 1, image: 1})[elem.type] ||
  215. name === 'select' ||
  216. name === 'textarea' ||
  217. elem.contentEditable === 'true'
  218. ) && !elem.disabled;
  219. },
  220. // any value, but not only whitespace
  221. filled: function(elem) {
  222. return !!trim($(elem).val());
  223. }
  224. });
  225. /**
  226. * Creates a new Validator
  227. *
  228. * @class
  229. * @param {Element} element - form element
  230. * @param {Object} options - options for validator
  231. */
  232. function Validator(element, options) {
  233. var me = this;
  234. if ( !(me instanceof Validator) ) {
  235. return new Validator(element, options);
  236. }
  237. if (Validator.pending) {
  238. $(window).on('validatorready', init);
  239. } else {
  240. init();
  241. }
  242. function init() {
  243. me.$el = $(element);
  244. if (me.$el.length) {
  245. me._init(me.$el[0], options);
  246. }
  247. else if (isString(element)) {
  248. preinitialized[element] = options;
  249. }
  250. }
  251. }
  252. Validator.prototype = {
  253. _init: function(element, options) {
  254. var me = this,
  255. opt, themeOpt, dataOpt;
  256. // Initialization options
  257. if ( isFunction(options) ) {
  258. options = {
  259. valid: options
  260. };
  261. }
  262. options = me._opt = options || {};
  263. dataOpt = attr(element, 'data-'+ NS +'-option');
  264. dataOpt = me._dataOpt = dataOpt && dataOpt.charAt(0) === '{' ? (new Function("return " + dataOpt))() : {};
  265. themeOpt = me._themeOpt = themes[ options.theme || dataOpt.theme || defaults.theme ];
  266. opt = me.options = $.extend({}, defaults, fieldDefaults, themeOpt, me.options, options, dataOpt);
  267. me.rules = new Rules(opt.rules, true);
  268. me.messages = new Messages(opt.messages, true);
  269. me.Field = _createFieldFactory(me);
  270. me.elements = me.elements || {};
  271. me.deferred = {};
  272. me.errors = {};
  273. me.fields = {};
  274. // Initialization fields
  275. me._initFields(opt.fields);
  276. // Initialization events and make a cache
  277. if ( !me.$el.data(NS) ) {
  278. me.$el.data(NS, me).addClass(CLS_WRAPPER +' '+ opt.formClass)
  279. .on('form-submit-validate', function(e, a, $form, opts, veto) {
  280. me.vetoed = veto.veto = !me.isValid;
  281. me.ajaxFormOptions = opts;
  282. })
  283. .on('submit'+ CLS_NS +' validate'+ CLS_NS, proxy(me, '_submit'))
  284. .on('reset'+ CLS_NS, proxy(me, '_reset'))
  285. .on('showmsg'+ CLS_NS, proxy(me, '_showmsg'))
  286. .on('hidemsg'+ CLS_NS, proxy(me, '_hidemsg'))
  287. .on('focusin'+ CLS_NS + ' click'+ CLS_NS, INPUT_SELECTOR, proxy(me, '_focusin'))
  288. .on('focusout'+ CLS_NS +' validate'+ CLS_NS, INPUT_SELECTOR, proxy(me, '_focusout'))
  289. .on('keyup'+ CLS_NS +' input'+ CLS_NS + ' compositionstart compositionend', INPUT_SELECTOR, proxy(me, '_focusout'))
  290. .on('click'+ CLS_NS, ':radio,:checkbox', 'click', proxy(me, '_focusout'))
  291. .on('change'+ CLS_NS, 'select,input[type="file"]', 'change', proxy(me, '_focusout'));
  292. // cache the novalidate attribute value
  293. me._NOVALIDATE = attr(element, NOVALIDATE);
  294. // Initialization is complete, stop off default HTML5 form validation
  295. // If use "jQuery.attr('novalidate')" in IE7 will complain: "SCRIPT3: Member not found."
  296. attr(element, NOVALIDATE, NOVALIDATE);
  297. }
  298. // Display all messages in target container
  299. if ( isString(opt.target) ) {
  300. me.$el.find(opt.target).addClass('msg-container');
  301. }
  302. },
  303. // Guess whether the form use ajax submit
  304. _guessAjax: function(form) {
  305. var me = this;
  306. if ( !(me.isAjaxSubmit = !!me.options.valid) ) {
  307. // if there is a "valid.form" event
  308. var events = ($._data || $.data)(form, "events");
  309. me.isAjaxSubmit = issetEvent(events, 'valid', 'form') || issetEvent(events, 'submit', 'form-plugin');
  310. }
  311. function issetEvent(events, name, namespace) {
  312. if ( events && events[name] &&
  313. $.map(events[name], function(e){
  314. return ~e.namespace.indexOf(namespace) ? 1 : null;
  315. }).length
  316. ) {
  317. return true;
  318. }
  319. return false;
  320. }
  321. },
  322. _initFields: function(fields) {
  323. var me = this, k, arr, i,
  324. clear = fields === null;
  325. // Processing field information
  326. if (clear) fields = me.fields;
  327. if ( isObject(fields) ) {
  328. for (k in fields) {
  329. if (~k.indexOf(',')) {
  330. arr = k.split(',');
  331. i = arr.length;
  332. while (i--) {
  333. initField(trim(arr[i]), fields[k]);
  334. }
  335. } else {
  336. initField(k, fields[k]);
  337. }
  338. }
  339. }
  340. // Parsing DOM rules
  341. me.$el.find(INPUT_SELECTOR).each(function() {
  342. me._parse(this);
  343. });
  344. function initField(k, v) {
  345. // delete a field from settings
  346. if ( v === null || clear ) {
  347. var el = me.elements[k];
  348. if (el) me._resetElement(el, true);
  349. delete me.fields[k];
  350. } else {
  351. me.fields[k] = new me.Field(k, isString(v) ? {rule: v} : v, me.fields[k]);
  352. }
  353. }
  354. },
  355. // Parsing a field
  356. _parse: function(el) {
  357. var me = this,
  358. field,
  359. key = el.name,
  360. display,
  361. timely,
  362. dataRule = attr(el, DATA_RULE);
  363. dataRule && attr(el, DATA_RULE, null);
  364. // If the field has passed the key as id mode, or it doesn't has a name
  365. if ( el.id && (
  366. ('#' + el.id in me.fields) ||
  367. !key ||
  368. // If dataRule and element are diffrent from old's, we use ID mode.
  369. (dataRule !== null && (field = me.fields[key]) && dataRule !== field.rule && el.id !== field.key)
  370. )
  371. ) {
  372. key = '#' + el.id;
  373. }
  374. // doesn't verify a field that has neither id nor name
  375. if (!key) return;
  376. field = me.getField(key, true);
  377. // The priority of passing parameter by DOM is higher than by JS.
  378. field.rule = dataRule || field.rule;
  379. if (display = attr(el, DATA_DISPLAY)) {
  380. field.display = display;
  381. }
  382. if (field.rule) {
  383. if ( attr(el, DATA_MUST) !== null || /\b(?:match|checked)\b/.test(field.rule) ) {
  384. field.must = true;
  385. }
  386. if ( /\brequired\b/.test(field.rule) ) {
  387. field.required = true;
  388. attr(el, ARIA_REQUIRED, true);
  389. }
  390. if (timely = attr(el, DATA_TIMELY)) {
  391. field.timely = +timely;
  392. } else if (field.timely > 3) {
  393. attr(el, DATA_TIMELY, field.timely);
  394. }
  395. me._parseRule(field);
  396. field.old = {};
  397. }
  398. if ( isString(field.target) ) {
  399. attr(el, DATA_TARGET, field.target);
  400. }
  401. if ( isString(field.tip) ) {
  402. attr(el, DATA_TIP, field.tip);
  403. }
  404. return me.fields[key] = field;
  405. },
  406. // Parsing field rules
  407. _parseRule: function(field) {
  408. var arr = rDisplay.exec(field.rule);
  409. if (!arr) return;
  410. // current rule index
  411. field._i = 0;
  412. if (arr[1]) {
  413. field.display = arr[1];
  414. }
  415. if (arr[2]) {
  416. field._rules = [];
  417. arr[2].replace(rRules, function(){
  418. var args = arguments;
  419. args[4] = args[4] || args[5];
  420. field._rules.push({
  421. and: args[1] === "&",
  422. not: args[2] === "!",
  423. or: args[6] === "|",
  424. method: args[3],
  425. params: args[4] ? $.map( args[4].split(', '), trim ) : undefined
  426. });
  427. });
  428. }
  429. },
  430. // Verify a zone
  431. _multiValidate: function($inputs, doneCallback){
  432. var me = this,
  433. opt = me.options;
  434. me.hasError = false;
  435. if (opt.ignore) {
  436. $inputs = $inputs.not(opt.ignore);
  437. }
  438. $inputs.each(function() {
  439. me._validate(this);
  440. if (me.hasError && opt.stopOnError) {
  441. // stop the validation
  442. return false;
  443. }
  444. });
  445. // Need to wait for all fields validation complete, especially asynchronous validation
  446. if (doneCallback) {
  447. me.validating = true;
  448. $.when.apply(
  449. null,
  450. $.map(me.deferred, function(v){return v;})
  451. ).done(function(){
  452. doneCallback.call(me, !me.hasError);
  453. me.validating = false;
  454. });
  455. }
  456. // If the form does not contain asynchronous validation, the return value is correct.
  457. // Otherwise, you should detect form validation result through "doneCallback".
  458. return !$.isEmptyObject(me.deferred) ? undefined : !me.hasError;
  459. },
  460. // Validate the whole form
  461. _submit: function(e) {
  462. var me = this,
  463. opt = me.options,
  464. form = e.target,
  465. canSubmit = e.type === 'submit' && !e.isDefaultPrevented();
  466. e.preventDefault();
  467. if (
  468. novalidateonce && ~(novalidateonce = false) ||
  469. // Prevent duplicate submission
  470. me.submiting ||
  471. // Receive the "validate" event only from the form.
  472. e.type === 'validate' && me.$el[0] !== form ||
  473. // trigger the beforeSubmit callback.
  474. isFunction(opt.beforeSubmit) && opt.beforeSubmit.call(me, form) === false
  475. ) {
  476. return;
  477. }
  478. if (me.isAjaxSubmit === undefined) {
  479. me._guessAjax(form);
  480. }
  481. me._debug('log', '\n<<< event: ' + e.type);
  482. me._reset();
  483. me.submiting = true;
  484. me._multiValidate(
  485. me.$el.find(INPUT_SELECTOR),
  486. function(isValid){
  487. var ret = (isValid || opt.debug === 2) ? 'valid' : 'invalid',
  488. errors;
  489. if (!isValid) {
  490. if (opt.focusInvalid) {
  491. // navigate to the error element
  492. me.$el.find('[' + ARIA_INVALID + ']:first').focus();
  493. }
  494. errors = $.map(me.errors, function(err){return err;});
  495. }
  496. // releasing submit
  497. me.submiting = false;
  498. me.isValid = isValid;
  499. // trigger callback and event
  500. isFunction(opt[ret]) && opt[ret].call(me, form, errors);
  501. me.$el.trigger(ret + CLS_NS_FORM, [form, errors]);
  502. me._debug('log', '>>> ' + ret);
  503. if (!isValid) return;
  504. // For jquery.form plugin
  505. if (me.vetoed) {
  506. $(form).ajaxSubmit(me.ajaxFormOptions);
  507. }
  508. else if (canSubmit && !me.isAjaxSubmit) {
  509. document.createElement('form').submit.call(form);
  510. }
  511. }
  512. );
  513. },
  514. _reset: function(e) {
  515. var me = this;
  516. me.errors = {};
  517. if (e) {
  518. me.reseting = true;
  519. me.$el.find(INPUT_SELECTOR).each( function(){
  520. me._resetElement(this);
  521. });
  522. delete me.reseting;
  523. }
  524. },
  525. _resetElement: function(el, all) {
  526. this._setClass(el, null);
  527. this.hideMsg(el);
  528. if (all) {
  529. attr(el, ARIA_REQUIRED, null);
  530. }
  531. },
  532. // Handle events: "focusin/click"
  533. _focusin: function(e) {
  534. var me = this,
  535. opt = me.options,
  536. el = e.target,
  537. timely,
  538. msg;
  539. if ( me.validating || ( e.type==='click' && document.activeElement === el ) ) {
  540. return;
  541. }
  542. if (opt.focusCleanup) {
  543. if ( attr(el, ARIA_INVALID) === 'true' ) {
  544. me._setClass(el, null);
  545. me.hideMsg(el);
  546. }
  547. }
  548. msg = attr(el, DATA_TIP);
  549. if (msg) {
  550. me.showMsg(el, {
  551. type: 'tip',
  552. msg: msg
  553. });
  554. } else {
  555. if (attr(el, DATA_RULE)) {
  556. me._parse(el);
  557. }
  558. if (timely = attr(el, DATA_TIMELY)) {
  559. if ( timely === 8 || timely === 9 ) {
  560. me._focusout(e);
  561. }
  562. }
  563. }
  564. },
  565. // Handle events: "focusout/validate/keyup/click/change/input/compositionstart/compositionend"
  566. _focusout: function(e) {
  567. var me = this,
  568. opt = me.options,
  569. el = e.target,
  570. etype = e.type,
  571. etype0,
  572. focusin = etype === 'focusin',
  573. special = etype === 'validate',
  574. elem,
  575. field,
  576. old,
  577. value,
  578. timestamp,
  579. key, specialKey,
  580. timely,
  581. timer = 0;
  582. if (etype === 'compositionstart') {
  583. me.pauseValidate = true;
  584. }
  585. if (etype === 'compositionend') {
  586. me.pauseValidate = false;
  587. }
  588. if (me.pauseValidate) {
  589. return;
  590. }
  591. // For checkbox and radio
  592. elem = el.name && _checkable(el) ? me.$el.find('input[name="'+ el.name +'"]').get(0) : el;
  593. // Get field
  594. if (!(field = me.getField(elem)) || !field.rule) {
  595. return;
  596. }
  597. // Cache event type
  598. etype0 = field._e;
  599. field._e = etype;
  600. timely = field.timely;
  601. if (!special) {
  602. if (!timely || (_checkable(el) && etype !== 'click')) {
  603. return;
  604. }
  605. value = field.getValue();
  606. // not validate field unless fill a value
  607. if ( field.ignoreBlank && !value && !focusin ) {
  608. me.hideMsg(el);
  609. return;
  610. }
  611. if ( etype === 'focusout' ) {
  612. if (etype0 === 'change') {
  613. return;
  614. }
  615. if ( timely === 2 || timely === 8 ) {
  616. old = field.old;
  617. if (value && old) {
  618. if (field.isValid && !old.showOk) {
  619. me.hideMsg(el);
  620. } else {
  621. me._makeMsg(el, field, old);
  622. }
  623. } else {
  624. return;
  625. }
  626. }
  627. }
  628. else {
  629. if ( timely < 2 && !e.data ) {
  630. return;
  631. }
  632. // mark timestamp to reduce the frequency of the received event
  633. timestamp = +new Date();
  634. if ( timestamp - (el._ts || 0) < 100 ) {
  635. return;
  636. }
  637. el._ts = timestamp;
  638. // handle keyup
  639. if ( etype === 'keyup' ) {
  640. if (etype0 === 'input') {
  641. return;
  642. }
  643. key = e.keyCode;
  644. specialKey = {
  645. 8: 1, // Backspace
  646. 9: 1, // Tab
  647. 16: 1, // Shift
  648. 32: 1, // Space
  649. 46: 1 // Delete
  650. };
  651. // only gets focus, no validation
  652. if ( key === 9 && !value ) {
  653. return;
  654. }
  655. // do not validate, if triggered by these keys
  656. if ( key < 48 && !specialKey[key] ) {
  657. return;
  658. }
  659. }
  660. if ( !focusin ) {
  661. // keyboard events, reducing the frequency of validation
  662. timer = timely <100 ? (etype === 'click' || el.tagName === 'SELECT') ? 0 : 400 : timely;
  663. }
  664. }
  665. }
  666. // if the current field is ignored
  667. if ( opt.ignore && $(el).is(opt.ignore) ) {
  668. return;
  669. }
  670. clearTimeout(field._t);
  671. if (timer) {
  672. field._t = setTimeout(function() {
  673. me._validate(el, field);
  674. }, timer);
  675. } else {
  676. if (special) field.old = {};
  677. me._validate(el, field);
  678. }
  679. },
  680. _setClass: function(el, isValid) {
  681. var $el = $(el), opt = this.options;
  682. if (opt.bindClassTo) {
  683. $el = $el.closest(opt.bindClassTo);
  684. }
  685. $el.removeClass( opt.invalidClass + ' ' + opt.validClass );
  686. if (isValid !== null) {
  687. $el.addClass( isValid ? opt.validClass : opt.invalidClass );
  688. }
  689. },
  690. _showmsg: function(e, type, msg) {
  691. var me = this,
  692. el = e.target;
  693. if ( me.$el.is(el) ) {
  694. if (isObject(type)) {
  695. me.showMsg(type)
  696. }
  697. else if ( type === 'tip' ) {
  698. me.$el.find(INPUT_SELECTOR +"["+ DATA_TIP +"]", el).each(function(){
  699. me.showMsg(this, {type: type, msg: msg});
  700. });
  701. }
  702. }
  703. else {
  704. me.showMsg(el, {type: type, msg: msg});
  705. }
  706. },
  707. _hidemsg: function(e) {
  708. var $el = $(e.target);
  709. if ( $el.is(INPUT_SELECTOR) ) {
  710. this.hideMsg($el);
  711. }
  712. },
  713. // Validated a field
  714. _validatedField: function(el, field, ret) {
  715. var me = this,
  716. opt = me.options,
  717. isValid = field.isValid = ret.isValid = !!ret.isValid,
  718. callback = isValid ? 'valid' : 'invalid';
  719. ret.key = field.key;
  720. ret.ruleName = field._r;
  721. ret.id = el.id;
  722. ret.value = field.value;
  723. me.elements[field.key] = ret.element = el;
  724. me.isValid = me.$el[0].isValid = isValid ? me.isFormValid() : isValid;
  725. if (isValid) {
  726. ret.type = 'ok';
  727. } else {
  728. if (me.submiting) {
  729. me.errors[field.key] = ret.msg;
  730. }
  731. me.hasError = true;
  732. }
  733. // cache result
  734. field.old = ret;
  735. // trigger callback
  736. isFunction(field[callback]) && field[callback].call(me, el, ret);
  737. isFunction(opt.validation) && opt.validation.call(me, el, ret);
  738. // trigger event
  739. $(el).attr( ARIA_INVALID, isValid ? null : true )
  740. .trigger( callback + CLS_NS_FIELD, [ret, me] );
  741. me.$el.triggerHandler('validation', [ret, me]);
  742. if (me.checkOnly) return;
  743. // set className
  744. me._setClass(el, ret.skip || ret.type === 'tip' ? null : isValid);
  745. me._makeMsg.apply(me, arguments);
  746. },
  747. _makeMsg: function(el, field, ret) {
  748. // show or hide the message
  749. if (field.msgMaker) {
  750. ret = $.extend({}, ret);
  751. if (field._e === 'focusin') {
  752. ret.type = 'tip';
  753. }
  754. this[ ret.showOk || ret.msg || ret.type === 'tip' ? 'showMsg' : 'hideMsg' ](el, ret, field);
  755. }
  756. },
  757. // Validated a rule
  758. _validatedRule: function(el, field, ret, msgOpt) {
  759. field = field || me.getField(el);
  760. msgOpt = msgOpt || {};
  761. var me = this,
  762. msg,
  763. rule,
  764. method = field._r,
  765. timely = field.timely,
  766. special = timely === 9 || timely === 8,
  767. transfer,
  768. temp,
  769. isValid = false;
  770. // use null to break validation from a field
  771. if (ret === null) {
  772. me._validatedField(el, field, {isValid: true, skip: true});
  773. field._i = 0;
  774. return;
  775. }
  776. else if (ret === undefined) {
  777. transfer = true;
  778. }
  779. else if (ret === true || ret === '') {
  780. isValid = true;
  781. }
  782. else if (isString(ret)) {
  783. msg = ret;
  784. }
  785. else if (isObject(ret)) {
  786. if (ret.error) {
  787. msg = ret.error;
  788. } else {
  789. msg = ret.ok;
  790. isValid = true;
  791. }
  792. }
  793. rule = field._rules[field._i];
  794. if (rule.not) {
  795. msg = undefined;
  796. isValid = method === "required" || !isValid;
  797. }
  798. if (rule.or) {
  799. if (isValid) {
  800. while ( field._i < field._rules.length && field._rules[field._i].or ) {
  801. field._i++;
  802. }
  803. } else {
  804. transfer = true;
  805. }
  806. }
  807. else if (rule.and) {
  808. if (!field.isValid) transfer = true;
  809. }
  810. if (transfer) {
  811. isValid = true;
  812. }
  813. // message analysis, and throw rule level event
  814. else {
  815. if (isValid) {
  816. if (field.showOk !== false) {
  817. temp = attr(el, DATA_OK);
  818. msg = temp === null ? isString(field.ok) ? field.ok : msg : temp;
  819. if (!isString(msg) && isString(field.showOk)) {
  820. msg = field.showOk;
  821. }
  822. if (isString(msg)) {
  823. msgOpt.showOk = isValid;
  824. }
  825. }
  826. }
  827. if (!isValid || special) {
  828. /* rule message priority:
  829. 1. custom DOM message
  830. 2. custom field message;
  831. 3. global defined message;
  832. 4. rule returned message;
  833. 5. default message;
  834. */
  835. msg = (_getDataMsg(el, field, msg || rule.msg || me.messages[method]) || me.messages.fallback).replace(/\{0\|?([^\}]*)\}/, function(m, defaultDisplay){
  836. return me._getDisplay(el, field.display) || defaultDisplay || me.messages[0];
  837. });
  838. }
  839. if (!isValid) field.isValid = isValid;
  840. msgOpt.msg = msg;
  841. $(el).trigger( (isValid ? 'valid' : 'invalid') + CLS_NS_RULE, [method, msg]);
  842. }
  843. if (special && (!transfer || rule.and)) {
  844. if (!isValid && !field._m) field._m = msg;
  845. field._v = field._v || [];
  846. field._v.push({
  847. type: isValid ? !transfer ? 'ok' : 'tip' : 'error',
  848. msg: msg || rule.msg
  849. });
  850. }
  851. me._debug('log', ' ' + field._i + ': ' + method + ' => ' + (isValid || msg));
  852. // the current rule has passed, continue to validate
  853. if ( (isValid || special) && field._i < field._rules.length - 1) {
  854. field._i++;
  855. me._checkRule(el, field);
  856. }
  857. // field was invalid, or all fields was valid
  858. else {
  859. field._i = 0;
  860. if (special) {
  861. msgOpt.isValid = field.isValid;
  862. msgOpt.result = field._v;
  863. msgOpt.msg = field._m || '';
  864. if (!field.value && (field._e === 'focusin')) {
  865. msgOpt.type = 'tip';
  866. }
  867. } else {
  868. msgOpt.isValid = isValid;
  869. }
  870. me._validatedField(el, field, msgOpt);
  871. delete field._m;
  872. delete field._v;
  873. }
  874. },
  875. // Verify a rule form a field
  876. _checkRule: function(el, field) {
  877. var me = this,
  878. ret,
  879. fn,
  880. old,
  881. key = field.key,
  882. rule = field._rules[field._i],
  883. method = rule.method,
  884. params = rule.params;
  885. // request has been sent, wait it
  886. if (me.submiting && me.deferred[key]) {
  887. return;
  888. }
  889. old = field.old;
  890. field._r = method;
  891. if (old && !field.must && !rule.must && rule.result !== undefined &&
  892. old.ruleName === method && old.id === el.id &&
  893. field.value && old.value === field.value )
  894. {
  895. // get result from cache
  896. ret = rule.result;
  897. }
  898. else {
  899. // get result from current rule
  900. fn = _getDataRule(el, method) || me.rules[method] || noop;
  901. ret = fn.call(field, el, params, field);
  902. if (fn.msg) rule.msg = fn.msg;
  903. }
  904. // asynchronous validation
  905. if (isObject(ret) && isFunction(ret.then)) {
  906. me.deferred[key] = ret;
  907. // whether the field valid is unknown
  908. field.isValid = undefined;
  909. // show loading message
  910. !me.checkOnly && me.showMsg(el, {
  911. type: 'loading',
  912. msg: me.messages.loading
  913. }, field);
  914. // waiting to parse the response data
  915. ret.then(
  916. function(d, textStatus, jqXHR) {
  917. var data = trim(jqXHR.responseText),
  918. result,
  919. dataFilter = field.dataFilter;
  920. // detect if data is json or jsonp format
  921. if (/jsonp?/.test(this.dataType)) {
  922. data = d;
  923. } else if (data.charAt(0) === '{') {
  924. data = $.parseJSON(data);
  925. }
  926. // filter data
  927. result = dataFilter.call(this, data, field);
  928. if (result === undefined) result = dataFilter.call(this, data.data, field);
  929. rule.data = this.data;
  930. rule.result = field.old ? result : undefined;
  931. me._validatedRule(el, field, result);
  932. },
  933. function(jqXHR, textStatus){
  934. me._validatedRule(el, field, me.messages[textStatus] || textStatus);
  935. }
  936. ).always(function(){
  937. delete me.deferred[key];
  938. });
  939. }
  940. // other result
  941. else {
  942. me._validatedRule(el, field, ret);
  943. }
  944. },
  945. // Processing the validation
  946. _validate: function(el, field) {
  947. var me = this;
  948. // doesn't validate the element that has "disabled" or "novalidate" attribute
  949. if ( el.disabled || attr(el, NOVALIDATE) !== null ) {
  950. return;
  951. }
  952. field = field || me.getField(el);
  953. if (!field) return;
  954. if (!field._rules) me._parse(el);
  955. if (!field._rules) return;
  956. me._debug('info', field.key);
  957. field.isValid = true;
  958. field.element = el;
  959. // Cache the value
  960. field.value = field.getValue();
  961. // if the field is not required, and that has a blank value
  962. if (!field.required && !field.must && !field.value) {
  963. if (!_checkable(el)) {
  964. me._validatedField(el, field, {isValid: true});
  965. return true;
  966. }
  967. }
  968. me._checkRule(el, field);
  969. return field.isValid;
  970. },
  971. _debug: function(type, messages) {
  972. if (window.console && this.options.debug) {
  973. console[type](messages);
  974. }
  975. },
  976. /**
  977. * Detecting whether the value of an element that matches a rule
  978. *
  979. * @method test
  980. * @param {Element} el - input element
  981. * @param {String} rule - rule name
  982. */
  983. test: function(el, rule) {
  984. var me = this,
  985. ret,
  986. parts = rRule.exec(rule),
  987. field,
  988. method,
  989. params;
  990. if (parts) {
  991. method = parts[1];
  992. if (method in me.rules) {
  993. params = parts[2] || parts[3];
  994. params = params ? params.split(', ') : undefined;
  995. field = me.getField(el, true);
  996. field._r = method;
  997. field.value = field.getValue();
  998. ret = me.rules[method].call(field, el, params);
  999. }
  1000. }
  1001. return ret === true || ret === undefined || ret === null;
  1002. },
  1003. _getDisplay: function(el, str) {
  1004. return !isString(str) ? isFunction(str) ? str.call(this, el) : '' : str;
  1005. },
  1006. _getMsgOpt: function(obj, field) {
  1007. var opt = field ? field : this.options;
  1008. return $.extend({
  1009. type: 'error',
  1010. pos: _getPos(opt.msgClass),
  1011. target: opt.target,
  1012. wrapper: opt.msgWrapper,
  1013. style: opt.msgStyle,
  1014. cls: opt.msgClass,
  1015. arrow: opt.msgArrow,
  1016. icon: opt.msgIcon
  1017. }, isString(obj) ? {msg: obj} : obj);
  1018. },
  1019. _getMsgDOM: function(el, msgOpt) {
  1020. var $el = $(el), $msgbox, datafor, tgt, container;
  1021. if ( $el.is(INPUT_SELECTOR) ) {
  1022. tgt = msgOpt.target || attr(el, DATA_TARGET);
  1023. if (tgt) {
  1024. tgt = isFunction(tgt) ? tgt.call(this, el) : this.$el.find(tgt);
  1025. if (tgt.length) {
  1026. if ( tgt.is(INPUT_SELECTOR) ) {
  1027. $el = tgt
  1028. el = tgt.get(0);
  1029. } else if ( tgt.hasClass(CLS_MSG_BOX) ) {
  1030. $msgbox = tgt;
  1031. } else {
  1032. container = tgt;
  1033. }
  1034. }
  1035. }
  1036. if (!$msgbox) {
  1037. datafor = (!_checkable(el) || !el.name) && el.id ? el.id : el.name;
  1038. $msgbox = this.$el.find(msgOpt.wrapper + '.' + CLS_MSG_BOX + '[for="' + datafor + '"]');
  1039. }
  1040. } else {
  1041. $msgbox = $el;
  1042. }
  1043. // Create new message box
  1044. if (!msgOpt.hide && !$msgbox.length) {
  1045. $msgbox = $('<'+ msgOpt.wrapper + '>').attr({
  1046. 'class': CLS_MSG_BOX + (msgOpt.cls ? ' ' + msgOpt.cls : ''),
  1047. 'style': msgOpt.style || undefined,
  1048. 'for': datafor
  1049. });
  1050. if ( _checkable(el) ) {
  1051. var $parent = $el.parent();
  1052. $msgbox.appendTo( $parent.is('label') ? $parent.parent() : $parent );
  1053. } else {
  1054. if (container) {
  1055. $msgbox.appendTo(container);
  1056. } else {
  1057. $msgbox[!msgOpt.pos || msgOpt.pos === 'right' ? 'insertAfter' : 'insertBefore']($el);
  1058. }
  1059. }
  1060. }
  1061. return $msgbox;
  1062. },
  1063. /**
  1064. * Show validation message
  1065. *
  1066. * @method showMsg
  1067. * @param {Element} el - input element
  1068. * @param {Object} msgOpt
  1069. */
  1070. showMsg: function(el, msgOpt, /*INTERNAL*/ field) {
  1071. if (!el) return;
  1072. var me = this,
  1073. opt = me.options,
  1074. msgShow,
  1075. msgMaker,
  1076. temp,
  1077. $msgbox;
  1078. if (isObject(el) && !el.jquery && !msgOpt) {
  1079. $.each(el, function(key, msg) {
  1080. var el = me.elements[key] || me.$el.find(_key2selector(key))[0];
  1081. me.showMsg(el, msg);
  1082. });
  1083. return;
  1084. }
  1085. if ($(el).is(INPUT_SELECTOR)) {
  1086. field = field || me.getField(el);
  1087. }
  1088. if (!(msgMaker = (field || opt).msgMaker)) {
  1089. return;
  1090. }
  1091. msgOpt = me._getMsgOpt(msgOpt, field);
  1092. el = (el.name && _checkable(el) ? me.$el.find('input[name="'+ el.name +'"]') : $(el)).get(0);
  1093. // ok or tip
  1094. if (!msgOpt.msg && msgOpt.type !== 'error') {
  1095. temp = attr(el, 'data-' + msgOpt.type);
  1096. if (temp !== null) msgOpt.msg = temp;
  1097. }
  1098. if ( !isString(msgOpt.msg) ) {
  1099. return;
  1100. }
  1101. $msgbox = me._getMsgDOM(el, msgOpt);
  1102. !rPos.test($msgbox[0].className) && $msgbox.addClass(msgOpt.cls);
  1103. if ( isIE === 6 && msgOpt.pos === 'bottom' ) {
  1104. $msgbox[0].style.marginTop = $(el).outerHeight() + 'px';
  1105. }
  1106. $msgbox.html( msgMaker.call(me, msgOpt) )[0].style.display = '';
  1107. if (isFunction(msgShow = field && field.msgShow || opt.msgShow)) {
  1108. msgShow.call(me, $msgbox, msgOpt.type);
  1109. }
  1110. },
  1111. /**
  1112. * Hide validation message
  1113. *
  1114. * @method hideMsg
  1115. * @param {Element} el - input element
  1116. * @param {Object} msgOpt optional
  1117. */
  1118. hideMsg: function(el, msgOpt, /*INTERNAL*/ field) {
  1119. var me = this,
  1120. opt = me.options,
  1121. msgHide,
  1122. $msgbox;
  1123. el = $(el).get(0);
  1124. if ($(el).is(INPUT_SELECTOR)) {
  1125. field = field || me.getField(el);
  1126. if (field) {
  1127. if (field.isValid || me.reseting) attr(el, ARIA_INVALID, null);
  1128. }
  1129. }
  1130. msgOpt = me._getMsgOpt(msgOpt, field);
  1131. msgOpt.hide = true;
  1132. $msgbox = me._getMsgDOM(el, msgOpt);
  1133. if (!$msgbox.length) return;
  1134. if ( isFunction(msgHide = field && field.msgHide || opt.msgHide) ) {
  1135. msgHide.call(me, $msgbox, msgOpt.type);
  1136. } else {
  1137. $msgbox[0].style.display = 'none';
  1138. $msgbox[0].innerHTML = null;
  1139. }
  1140. },
  1141. /**
  1142. * Get field information
  1143. *
  1144. * @method getField
  1145. * @param {Element} - input element
  1146. * @return {Object} field
  1147. */
  1148. getField: function(el, must) {
  1149. var me = this,
  1150. key,
  1151. field;
  1152. if (isString(el)) {
  1153. key = el;
  1154. el = undefined;
  1155. } else {
  1156. if (attr(el, DATA_RULE)) {
  1157. return me._parse(el);
  1158. }
  1159. if (el.id && '#' + el.id in me.fields || !el.name) {
  1160. key = '#' + el.id;
  1161. } else {
  1162. key = el.name;
  1163. }
  1164. }
  1165. if ( (field = me.fields[key]) || must && (field = new me.Field(key)) ) {
  1166. field.element = el;
  1167. }
  1168. return field;
  1169. },
  1170. /**
  1171. * Config a field
  1172. *
  1173. * @method: setField
  1174. * @param {String} key
  1175. * @param {Object} obj
  1176. */
  1177. setField: function(key, obj) {
  1178. var fields = {};
  1179. if (!key) return;
  1180. // update this field
  1181. if (isString(key)) {
  1182. fields[key] = obj;
  1183. }
  1184. // update fields
  1185. else {
  1186. fields = key;
  1187. }
  1188. this._initFields(fields);
  1189. },
  1190. /**
  1191. * Detecting whether the form is valid
  1192. *
  1193. * @method isFormValid
  1194. * @return {Boolean}
  1195. */
  1196. isFormValid: function() {
  1197. var fields = this.fields, k, field;
  1198. for (k in fields) {
  1199. field = fields[k];
  1200. if (!field._rules || !field.required && !field.must && !field.value) continue;
  1201. if (!field.isValid) return false;
  1202. }
  1203. return true;
  1204. },
  1205. /**
  1206. * Prevent submission form
  1207. *
  1208. * @method holdSubmit
  1209. * @param {Boolean} hold - If set to false, will release the hold
  1210. */
  1211. holdSubmit: function(hold) {
  1212. this.submiting = hold === undefined || hold;
  1213. },
  1214. /**
  1215. * Clean validation messages
  1216. *
  1217. * @method cleanUp
  1218. */
  1219. cleanUp: function() {
  1220. this._reset(1);
  1221. },
  1222. /**
  1223. * Destroy the validation
  1224. *
  1225. * @method destroy
  1226. */
  1227. destroy: function() {
  1228. this._reset(1);
  1229. this.$el.off(CLS_NS).removeData(NS);
  1230. attr(this.$el[0], NOVALIDATE, this._NOVALIDATE);
  1231. }
  1232. };
  1233. /**
  1234. * Create Field Factory
  1235. *
  1236. * @class
  1237. * @param {Object} context
  1238. * @return {Function} Factory
  1239. */
  1240. function _createFieldFactory(context) {
  1241. function FieldFactory() {
  1242. var options = this.options;
  1243. for (var i in options) {
  1244. if (i in fieldDefaults) this[i] = options[i];
  1245. }
  1246. $.extend(this, {
  1247. _valHook: function() {
  1248. return this.element.contentEditable === 'true' ? 'text' : 'val';
  1249. },
  1250. getValue: function() {
  1251. var elem = this.element;
  1252. if (elem.type === "number" && elem.validity && elem.validity.badInput) {
  1253. return 'NaN';
  1254. }
  1255. return $(elem)[this._valHook()]();
  1256. },
  1257. setValue: function(value) {
  1258. $(this.element)[this._valHook()](this.value = value);
  1259. },
  1260. // Get a range of validation messages
  1261. getRangeMsg: function(value, params, suffix) {
  1262. if (!params) return;
  1263. var me = this,
  1264. msg = me.messages[me._r] || '',
  1265. result,
  1266. p = params[0].split('~'),
  1267. e = params[1] === 'false',
  1268. a = p[0],
  1269. b = p[1],
  1270. c = 'rg',
  1271. args = [''],
  1272. isNumber = trim(value) && +value === +value;
  1273. function compare(large, small) {
  1274. return !e ? large >= small : large > small;
  1275. }
  1276. if (p.length === 2) {
  1277. if (a && b) {
  1278. if (isNumber && compare(value, +a) && compare(+b, value)) {
  1279. result = true;
  1280. }
  1281. args = args.concat(p);
  1282. c = e ? 'gtlt' : 'rg';
  1283. }
  1284. else if (a && !b) {
  1285. if (isNumber && compare(value, +a)) {
  1286. result = true;
  1287. }
  1288. args.push(a);
  1289. c = e ? 'gt' : 'gte';
  1290. }
  1291. else if (!a && b) {
  1292. if (isNumber && compare(+b, value)) {
  1293. result = true;
  1294. }
  1295. args.push(b);
  1296. c = e ? 'lt' : 'lte';
  1297. }
  1298. }
  1299. else {
  1300. if (value === +a) {
  1301. result = true;
  1302. }
  1303. args.push(a);
  1304. c = 'eq';
  1305. }
  1306. if (msg) {
  1307. if (suffix && msg[c + suffix]) {
  1308. c += suffix;
  1309. }
  1310. args[0] = msg[c];
  1311. }
  1312. return result || me._rules && ( me._rules[me._i].msg = me.renderMsg.apply(null, args) );
  1313. },
  1314. // Render message template
  1315. renderMsg: function() {
  1316. var args = arguments,
  1317. tpl = args[0],
  1318. i = args.length;
  1319. if (!tpl) return;
  1320. while (--i) {
  1321. tpl = tpl.replace('{' + i + '}', args[i]);
  1322. }
  1323. return tpl;
  1324. }
  1325. });
  1326. }
  1327. function Field(key, obj, oldField) {
  1328. this.key = key;
  1329. this.validator = context;
  1330. $.extend(this, oldField, obj);
  1331. }
  1332. FieldFactory.prototype = context;
  1333. Field.prototype = new FieldFactory();
  1334. return Field;
  1335. }
  1336. /**
  1337. * Create Rules
  1338. *
  1339. * @class
  1340. * @param {Object} obj rules
  1341. * @param {Object} context context
  1342. */
  1343. function Rules(obj, context) {
  1344. if (!isObject(obj)) return;
  1345. var k, that = context ? context === true ? this : context : Rules.prototype;
  1346. for (k in obj) {
  1347. if (_checkRuleName(k))
  1348. that[k] = _getRule(obj[k]);
  1349. }
  1350. }
  1351. /**
  1352. * Create Messages
  1353. *
  1354. * @class
  1355. * @param {Object} obj rules
  1356. * @param {Object} context context
  1357. */
  1358. function Messages(obj, context) {
  1359. if (!isObject(obj)) return;
  1360. var k, that = context ? context === true ? this : context : Messages.prototype;
  1361. for (k in obj) {
  1362. that[k] = obj[k];
  1363. }
  1364. }
  1365. // Rule converted factory
  1366. function _getRule(fn) {
  1367. switch ($.type(fn)) {
  1368. case 'function':
  1369. return fn;
  1370. case 'array':
  1371. var f = function() {
  1372. return fn[0].test(this.value) || fn[1] || false;
  1373. };
  1374. f.msg = fn[1];
  1375. return f;
  1376. case 'regexp':
  1377. return function() {
  1378. return fn.test(this.value);
  1379. };
  1380. }
  1381. }
  1382. // Get instance by an element
  1383. function _getInstance(el) {
  1384. var wrap, k, options;
  1385. if (!el || !el.tagName) return;
  1386. switch (el.tagName) {
  1387. case 'INPUT':
  1388. case 'SELECT':
  1389. case 'TEXTAREA':
  1390. case 'BUTTON':
  1391. case 'FIELDSET':
  1392. wrap = el.form || $(el).closest('.' + CLS_WRAPPER);
  1393. break;
  1394. case 'FORM':
  1395. wrap = el;
  1396. break;
  1397. default:
  1398. wrap = $(el).closest('.' + CLS_WRAPPER);
  1399. }
  1400. for (k in preinitialized) {
  1401. if ($(wrap).is(k)) {
  1402. options = preinitialized[k];
  1403. break;
  1404. }
  1405. }
  1406. return $(wrap).data(NS) || $(wrap)[NS](options).data(NS);
  1407. }
  1408. // Get custom rules on the node
  1409. function _getDataRule(el, method) {
  1410. var fn = trim(attr(el, DATA_RULE + '-' + method));
  1411. if ( fn && (fn = new Function("return " + fn)()) ) {
  1412. return _getRule(fn);
  1413. }
  1414. }
  1415. // Get custom messages on the node
  1416. function _getDataMsg(el, field, m) {
  1417. var msg = field.msg,
  1418. item = field._r;
  1419. if ( isObject(msg) ) msg = msg[item];
  1420. if ( !isString(msg) ) {
  1421. msg = attr(el, DATA_MSG + '-' + item) || attr(el, DATA_MSG) || ( m ? isString(m) ? m : m[item] : '');
  1422. }
  1423. return msg;
  1424. }
  1425. // Get message position
  1426. function _getPos(str) {
  1427. var pos;
  1428. if (str) pos = rPos.exec(str);
  1429. return pos && pos[0];
  1430. }
  1431. // Check whether the element is checkbox or radio
  1432. function _checkable(el) {
  1433. return el.tagName === 'INPUT' && el.type === 'checkbox' || el.type === 'radio';
  1434. }
  1435. // Parse date string to timestamp
  1436. function _parseDate(str) {
  1437. return Date.parse(str.replace(/\.|\-/g, '/'));
  1438. }
  1439. // Rule name only allows alphanumeric characters and underscores
  1440. function _checkRuleName(name) {
  1441. return /^\w+$/.test(name);
  1442. }
  1443. // Translate field key to jQuery selector.
  1444. function _key2selector(key) {
  1445. var isID = key.charAt(0) === "#";
  1446. key = key.replace(/([:.{(|)}/\[\]])/g, "\\$1");
  1447. return isID ? key : '[name="'+ key +'"]:first';
  1448. }
  1449. // Fixed a issue cause by refresh page in IE.
  1450. $(window).on('beforeunload', function(){
  1451. this.focus();
  1452. });
  1453. $(document)
  1454. .on('click', ':submit', function(){
  1455. var input = this, attrNode;
  1456. if (!input.form) return;
  1457. // Shim for "formnovalidate"
  1458. attrNode = input.getAttributeNode('formnovalidate');
  1459. if (attrNode && attrNode.nodeValue !== null || attr(input, NOVALIDATE)!== null) {
  1460. novalidateonce = true;
  1461. }
  1462. })
  1463. // Automatic initializing form validation
  1464. .on('focusin submit validate', 'form,.'+CLS_WRAPPER, function(e) {
  1465. if ( attr(this, NOVALIDATE) !== null ) return;
  1466. var $form = $(this), me;
  1467. if ( !$form.data(NS) && (me = _getInstance(this)) ) {
  1468. if ( !$.isEmptyObject(me.fields) ) {
  1469. // Execute event handler
  1470. if (e.type === 'focusin') {
  1471. me._focusin(e);
  1472. } else {
  1473. me._submit(e);
  1474. }
  1475. } else {
  1476. attr(this, NOVALIDATE, NOVALIDATE);
  1477. $form.off(CLS_NS).removeData(NS);
  1478. }
  1479. }
  1480. });
  1481. new Messages({
  1482. fallback: "This field is not valid.",
  1483. loading: 'Validating...'
  1484. });
  1485. // Built-in rules (global)
  1486. new Rules({
  1487. /**
  1488. * required
  1489. *
  1490. * @example:
  1491. required
  1492. required(anotherRule)
  1493. required(not, -1)
  1494. required(from, .contact)
  1495. */
  1496. required: function(element, params) {
  1497. var me = this,
  1498. val = trim(me.value),
  1499. isValid = true;
  1500. if (params) {
  1501. if ( params.length === 1 ) {
  1502. if ( !_checkRuleName(params[0]) ) {
  1503. if (!val && !$(params[0], me.$el).length ) {
  1504. return null;
  1505. }
  1506. }
  1507. else if ( me.rules[params[0]] ) {
  1508. if ( !val && !me.test(element, params[0]) ) {
  1509. attr(element, ARIA_REQUIRED, null);
  1510. return null;
  1511. } else {
  1512. attr(element, ARIA_REQUIRED, true);
  1513. }
  1514. }
  1515. }
  1516. else if ( params[0] === 'not' ) {
  1517. $.each(params.slice(1), function() {
  1518. return (isValid = val !== trim(this));
  1519. });
  1520. }
  1521. else if ( params[0] === 'from' ) {
  1522. var $elements = me.$el.find(params[1]),
  1523. VALIDATED = '_validated_',
  1524. ret;
  1525. isValid = $elements.filter(function(){
  1526. var field = me.getField(this);
  1527. return field && !!trim(field.getValue());
  1528. }).length >= (params[2] || 1);
  1529. if (isValid) {
  1530. if (!val) ret = null;
  1531. } else {
  1532. ret = _getDataMsg($elements[0], me) || false;
  1533. }
  1534. if ( !$(element).data(VALIDATED) ) {
  1535. $elements.data(VALIDATED, 1).each(function(){
  1536. if (element !== this) {
  1537. me._validate(this);
  1538. }
  1539. }).removeData(VALIDATED);
  1540. }
  1541. return ret;
  1542. }
  1543. }
  1544. return isValid && !!val;
  1545. },
  1546. /**
  1547. * integer
  1548. *
  1549. * @example:
  1550. integer
  1551. integer[+]
  1552. integer[+0]
  1553. integer[-]
  1554. integer[-0]
  1555. */
  1556. integer: function(element, params) {
  1557. var re, z = '0|',
  1558. p = '[1-9]\\d*',
  1559. key = params ? params[0] : '*';
  1560. switch (key) {
  1561. case '+':
  1562. re = p;
  1563. break;
  1564. case '-':
  1565. re = '-' + p;
  1566. break;
  1567. case '+0':
  1568. re = z + p;
  1569. break;
  1570. case '-0':
  1571. re = z + '-' + p;
  1572. break;
  1573. default:
  1574. re = z + '-?' + p;
  1575. }
  1576. re = '^(?:' + re + ')$';
  1577. return new RegExp(re).test(this.value) || this.messages.integer[key];
  1578. },
  1579. /**
  1580. * match another field
  1581. *
  1582. * @example:
  1583. match[password] Match the password field (two values ​​must be the same)
  1584. match[eq, password] Ditto
  1585. match[neq, count] The value must be not equal to the value of the count field
  1586. match[lt, count] The value must be less than the value of the count field
  1587. match[lte, count] The value must be less than or equal to the value of the count field
  1588. match[gt, count] The value must be greater than the value of the count field
  1589. match[gte, count] The value must be greater than or equal to the value of the count field
  1590. match[gte, startDate, date]
  1591. match[gte, startTime, time]
  1592. **/
  1593. match: function(element, params) {
  1594. if (!params) return;
  1595. var me = this,
  1596. a, b,
  1597. key, msg, type = 'eq', parser,
  1598. selector2, elem2, field2;
  1599. if (params.length === 1) {
  1600. key = params[0];
  1601. } else {
  1602. type = params[0];
  1603. key = params[1];
  1604. }
  1605. selector2 = _key2selector(key);
  1606. elem2 = me.$el.find(selector2)[0];
  1607. // If the compared field is not exist
  1608. if (!elem2) return;
  1609. field2 = me.getField(elem2);
  1610. a = me.value;
  1611. b = field2.getValue();
  1612. if (!me._match) {
  1613. me.$el.on('valid'+CLS_NS_FIELD+CLS_NS, selector2, function(){
  1614. $(element).trigger('validate');
  1615. });
  1616. me._match = field2._match = 1;
  1617. }
  1618. // If both fields are blank
  1619. if (!me.required && a === "" && b === "") {
  1620. return null;
  1621. }
  1622. parser = params[2];
  1623. if (parser) {
  1624. if (/^date(time)?$/i.test(parser)) {
  1625. a = _parseDate(a);
  1626. b = _parseDate(b);
  1627. } else if (parser === 'time') {
  1628. a = +a.replace(/:/g, '');
  1629. b = +b.replace(/:/g, '');
  1630. }
  1631. }
  1632. // If the compared field is incorrect, we only ensure that this field is correct.
  1633. if (type !== "eq" && !isNaN(+a) && isNaN(+b)) {
  1634. return true;
  1635. }
  1636. msg = me.messages.match[type].replace( '{1}', me._getDisplay( element, field2.display || key ) );
  1637. switch (type) {
  1638. case 'lt':
  1639. return (+a < +b) || msg;
  1640. case 'lte':
  1641. return (+a <= +b) || msg;
  1642. case 'gte':
  1643. return (+a >= +b) || msg;
  1644. case 'gt':
  1645. return (+a > +b) || msg;
  1646. case 'neq':
  1647. return (a !== b) || msg;
  1648. default:
  1649. return (a === b) || msg;
  1650. }
  1651. },
  1652. /**
  1653. * range numbers
  1654. *
  1655. * @example:
  1656. range[0~99] Number 0-99
  1657. range[0~] Number greater than or equal to 0
  1658. range[~100] Number less than or equal to 100
  1659. **/
  1660. range: function(element, params) {
  1661. return this.getRangeMsg(this.value, params);
  1662. },
  1663. /**
  1664. * how many checkbox or radio inputs that checked
  1665. *
  1666. * @example:
  1667. checked; no empty, same to required
  1668. checked[1~3] 1-3 items
  1669. checked[1~] greater than 1 item
  1670. checked[~3] less than 3 items
  1671. checked[3] 3 items
  1672. **/
  1673. checked: function(element, params) {
  1674. if ( !_checkable(element) ) return;
  1675. var me = this,
  1676. elem, count;
  1677. if (element.name) {
  1678. count = me.$el.find('input[name="' + element.name + '"]').filter(function() {
  1679. var el = this;
  1680. if (!elem && _checkable(el)) elem = el;
  1681. return !el.disabled && el.checked;
  1682. }).length;
  1683. } else {
  1684. elem = element;
  1685. count = elem.checked;
  1686. }
  1687. if (params) {
  1688. return me.getRangeMsg(count, params);
  1689. } else {
  1690. return !!count || _getDataMsg(elem, me, '') || me.messages.required;
  1691. }
  1692. },
  1693. /**
  1694. * length of a characters (You can pass the second parameter "true", will calculate the length in bytes)
  1695. *
  1696. * @example:
  1697. length[6~16] 6-16 characters
  1698. length[6~] Greater than 6 characters
  1699. length[~16] Less than 16 characters
  1700. length[~16, true] Less than 16 characters, non-ASCII characters calculating two-character
  1701. **/
  1702. length: function(element, params) {
  1703. var value = this.value,
  1704. len = (params[1] === 'true' ? value.replace(rDoubleBytes, 'xx') : value).length;
  1705. return this.getRangeMsg(len, params, (params[1] ? '_2' : ''));
  1706. },
  1707. /**
  1708. * remote validation
  1709. *
  1710. * @description
  1711. * remote([get:]url [, name1, [name2 ...]]);
  1712. * Adaptation three kinds of results (Front for the successful, followed by a failure):
  1713. 1. text:
  1714. '' 'Error Message'
  1715. 2. json:
  1716. {"ok": ""} {"error": "Error Message"}
  1717. 3. json wrapper:
  1718. {"status": 1, "data": {"ok": ""}} {"status": 1, "data": {"error": "Error Message"}}
  1719. * @example
  1720. The simplest: remote(path/to/server);
  1721. With parameters: remote(path/to/server, name1, name2, ...);
  1722. By GET: remote(get:path/to/server, name1, name2, ...);
  1723. Name proxy: remote(path/to/server, name1, proxyname2:name2, proxyname3:#id3, ...)
  1724. Query String remote(path/to/server, foo=1&bar=2, name1, name2, ...)
  1725. */
  1726. remote: function(element, params) {
  1727. if (!params) return;
  1728. var me = this,
  1729. arr = rAjaxType.exec(params[0]),
  1730. rule = me._rules[me._i],
  1731. data = {},
  1732. queryString = '',
  1733. url = arr[3],
  1734. type = arr[2] || 'POST', // GET / POST
  1735. rType = (arr[1]||'').toLowerCase(), // CORS / JSONP
  1736. dataType;
  1737. rule.must = true;
  1738. data[element.name] = me.value;
  1739. // There are extra fields
  1740. if (params[1]) {
  1741. $.map(params.slice(1), function(name) {
  1742. var arr, key;
  1743. if (~name.indexOf('=')) {
  1744. queryString += '&' + name;
  1745. } else {
  1746. arr = name.split(':');
  1747. name = trim(arr[0]);
  1748. key = trim(arr[1]) || name;
  1749. data[ name ] = me.$el.find( _key2selector(key) ).val();
  1750. }
  1751. });
  1752. }
  1753. data = $.param(data) + queryString;
  1754. if (!me.must && rule.data && rule.data === data) {
  1755. return rule.result;
  1756. }
  1757. // Cross-domain request, force jsonp dataType
  1758. if (rType !== 'cors' && /^https?:/.test(url) && !~url.indexOf(location.host)) {
  1759. dataType = 'jsonp';
  1760. }
  1761. // Asynchronous validation need return jqXHR objects
  1762. return $.ajax({
  1763. url: url,
  1764. type: type,
  1765. data: data,
  1766. dataType: dataType
  1767. });
  1768. },
  1769. /**
  1770. * filter characters, direct filtration without prompting error (support custom regular expressions)
  1771. *
  1772. * @example
  1773. * filter filtering unsafe characters
  1774. * filter(regexp) filtering the "regexp" matched characters
  1775. */
  1776. filter: function(element, params) {
  1777. var value = this.value,
  1778. temp = value.replace( params ? (new RegExp("[" + params[0] + "]", "gm")) : rUnsafe, '' );
  1779. if (temp !== value) this.setValue(temp);
  1780. }
  1781. });
  1782. /**
  1783. * Config global options
  1784. *
  1785. * @static config
  1786. * @param {Object} options
  1787. */
  1788. Validator.config = function(key, value) {
  1789. if (isObject(key)) {
  1790. $.each(key, _config);
  1791. }
  1792. else if (isString(key)) {
  1793. _config(key, value);
  1794. }
  1795. function _config(k, o) {
  1796. if (k === 'rules') {
  1797. new Rules(o);
  1798. }
  1799. else if (k === 'messages') {
  1800. new Messages(o);
  1801. }
  1802. else if (k in fieldDefaults) {
  1803. fieldDefaults[k] = o;
  1804. }
  1805. else {
  1806. defaults[k] = o;
  1807. }
  1808. }
  1809. };
  1810. /**
  1811. * Config themes
  1812. *
  1813. * @static setTheme
  1814. * @param {String|Object} name
  1815. * @param {Object} obj
  1816. * @example
  1817. .setTheme( themeName, themeOptions )
  1818. .setTheme( multiThemes )
  1819. */
  1820. Validator.setTheme = function(name, obj) {
  1821. if ( isObject(name) ) {
  1822. $.extend(true, themes, name);
  1823. }
  1824. else if ( isString(name) && isObject(obj) ) {
  1825. themes[name] = $.extend(themes[name], obj);
  1826. }
  1827. };
  1828. /**
  1829. * Resource loader
  1830. *
  1831. * @static load
  1832. * @param {String} str
  1833. * @example
  1834. .load('local=zh-CN') // load: local/zh-CN.js and jquery.validator.css
  1835. .load('local=zh-CN&css=') // load: local/zh-CN.js
  1836. .load('local&css') // load: local/en.js (set <html lang="en">) and jquery.validator.css
  1837. .load('local') // dito
  1838. */
  1839. Validator.load = function(str) {
  1840. if (!str) return;
  1841. var doc = document,
  1842. params = {},
  1843. node = doc.scripts[0],
  1844. dir, el, ONLOAD;
  1845. str.replace(/([^?=&]+)=([^&#]*)/g, function(m, key, value){
  1846. params[key] = value;
  1847. });
  1848. dir = params.dir || Validator.dir;
  1849. if (!Validator.css && params.css !== '') {
  1850. el = doc.createElement('link');
  1851. el.rel = 'stylesheet';
  1852. el.href = Validator.css = dir + 'jquery.validator.css';
  1853. node.parentNode.insertBefore(el, node);
  1854. }
  1855. if (!Validator.local && ~str.indexOf('local') && params.local !== '') {
  1856. Validator.local = (params.local || doc.documentElement.lang || 'en').replace('_','-');
  1857. Validator.pending = 1;
  1858. el = doc.createElement('script');
  1859. el.src = dir + 'local/' + Validator.local + '.js';
  1860. ONLOAD = 'onload' in el ? 'onload' : 'onreadystatechange';
  1861. el[ONLOAD] = function() {
  1862. if (!el.readyState || /loaded|complete/.test(el.readyState)) {
  1863. el = el[ONLOAD] = null;
  1864. delete Validator.pending;
  1865. $(window).triggerHandler('validatorready');
  1866. }
  1867. };
  1868. node.parentNode.insertBefore(el, node);
  1869. }
  1870. };
  1871. // Auto loading resources
  1872. (function(){
  1873. var scripts = document.scripts,
  1874. i = scripts.length, node, arr,
  1875. re = /(.*validator(?:\.min)?.js)(\?.*(?:local|css|dir)(?:=[\w\-]*)?)?/;
  1876. while (i-- && !arr) {
  1877. node = scripts[i];
  1878. arr = (node.hasAttribute ? node.src : node.getAttribute('src',4)||'').match(re);
  1879. }
  1880. if (!arr) return;
  1881. Validator.dir = arr[1].split('/').slice(0, -1).join('/')+'/';
  1882. Validator.load(arr[2]);
  1883. })();
  1884. return $[NS] = Validator;
  1885. }));