vee-validate.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101
  1. /**
  2. * vee-validate v2.0.0-beta.24
  3. * (c) 2017 Abdelrahman Awad
  4. * @license MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global.VeeValidate = factory());
  10. }(this, (function () { 'use strict';
  11. var alpha = function (value) { return /^[a-zA-Z]*$/.test(value); };
  12. var alpha_dash = function (value) { return /^[a-zA-Z0-9_-]*$/.test(value); };
  13. var alpha_num = function (value) { return /^[a-zA-Z0-9]*$/.test(value); };
  14. var alpha_spaces = function (value) { return /^[a-zA-Z\s]*$/.test(value); };
  15. var between = function (value, ref) {
  16. var min = ref[0];
  17. var max = ref[1];
  18. return Number(min) <= value && Number(max) >= value;
  19. };
  20. var confirmed = function (value, ref, validatingField) {
  21. var confirmedField = ref[0];
  22. var field = confirmedField
  23. ? document.querySelector(("input[name='" + confirmedField + "']"))
  24. : document.querySelector(("input[name='" + validatingField + "_confirmation']"));
  25. return !! (field && String(value) === field.value);
  26. };
  27. function unwrapExports (x) {
  28. return x && x.__esModule ? x['default'] : x;
  29. }
  30. function createCommonjsModule(fn, module) {
  31. return module = { exports: {} }, fn(module, module.exports), module.exports;
  32. }
  33. var assertString_1 = createCommonjsModule(function (module, exports) {
  34. 'use strict';
  35. Object.defineProperty(exports, "__esModule", {
  36. value: true
  37. });
  38. exports.default = assertString;
  39. function assertString(input) {
  40. if (typeof input !== 'string') {
  41. throw new TypeError('This library (validator.js) validates strings only');
  42. }
  43. }
  44. module.exports = exports['default'];
  45. });
  46. var isCreditCard_1 = createCommonjsModule(function (module, exports) {
  47. 'use strict';
  48. Object.defineProperty(exports, "__esModule", {
  49. value: true
  50. });
  51. exports.default = isCreditCard;
  52. var _assertString = assertString_1;
  53. var _assertString2 = _interopRequireDefault(_assertString);
  54. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  55. /* eslint-disable max-len */
  56. var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})|62[0-9]{14}$/;
  57. /* eslint-enable max-len */
  58. function isCreditCard(str) {
  59. (0, _assertString2.default)(str);
  60. var sanitized = str.replace(/[^0-9]+/g, '');
  61. if (!creditCard.test(sanitized)) {
  62. return false;
  63. }
  64. var sum = 0;
  65. var digit = void 0;
  66. var tmpNum = void 0;
  67. var shouldDouble = void 0;
  68. for (var i = sanitized.length - 1; i >= 0; i--) {
  69. digit = sanitized.substring(i, i + 1);
  70. tmpNum = parseInt(digit, 10);
  71. if (shouldDouble) {
  72. tmpNum *= 2;
  73. if (tmpNum >= 10) {
  74. sum += tmpNum % 10 + 1;
  75. } else {
  76. sum += tmpNum;
  77. }
  78. } else {
  79. sum += tmpNum;
  80. }
  81. shouldDouble = !shouldDouble;
  82. }
  83. return !!(sum % 10 === 0 ? sanitized : false);
  84. }
  85. module.exports = exports['default'];
  86. });
  87. var isCreditCard = unwrapExports(isCreditCard_1);
  88. var credit_card = function (value) { return isCreditCard(String(value)); };
  89. var decimal = function (value, params) {
  90. var decimals = Array.isArray(params) ? (params[0] || '*') : '*';
  91. if (Array.isArray(value)) {
  92. return false;
  93. }
  94. if (value === null || value === undefined || value === '') {
  95. return true;
  96. }
  97. // if is 0.
  98. if (Number(decimals) === 0) {
  99. return /^-?\d*$/.test(value);
  100. }
  101. var regexPart = decimals === '*' ? '+' : ("{1," + decimals + "}");
  102. var regex = new RegExp(("^-?\\d*(\\.\\d" + regexPart + ")?$"));
  103. if (! regex.test(value)) {
  104. return false;
  105. }
  106. var parsedValue = parseFloat(value);
  107. // eslint-disable-next-line
  108. return parsedValue === parsedValue;
  109. };
  110. var digits = function (value, ref) {
  111. var length = ref[0];
  112. var strVal = String(value);
  113. return /^[0-9]*$/.test(strVal) && strVal.length === Number(length);
  114. };
  115. var validateImage = function (file, width, height) {
  116. var URL = window.URL || window.webkitURL;
  117. return new Promise(function (resolve) {
  118. var image = new Image();
  119. image.onerror = function () { return resolve({ valid: false }); };
  120. image.onload = function () { return resolve({
  121. valid: image.width === Number(width) && image.height === Number(height)
  122. }); };
  123. image.src = URL.createObjectURL(file);
  124. });
  125. };
  126. var dimensions = function (files, ref) {
  127. var width = ref[0];
  128. var height = ref[1];
  129. var list = [];
  130. for (var i = 0; i < files.length; i++) {
  131. // if file is not an image, reject.
  132. if (! /\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(files[i].name)) {
  133. return false;
  134. }
  135. list.push(files[i]);
  136. }
  137. return Promise.all(list.map(function (file) { return validateImage(file, width, height); }));
  138. };
  139. var merge_1 = createCommonjsModule(function (module, exports) {
  140. 'use strict';
  141. Object.defineProperty(exports, "__esModule", {
  142. value: true
  143. });
  144. exports.default = merge;
  145. function merge() {
  146. var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  147. var defaults = arguments[1];
  148. for (var key in defaults) {
  149. if (typeof obj[key] === 'undefined') {
  150. obj[key] = defaults[key];
  151. }
  152. }
  153. return obj;
  154. }
  155. module.exports = exports['default'];
  156. });
  157. var isByteLength_1 = createCommonjsModule(function (module, exports) {
  158. 'use strict';
  159. Object.defineProperty(exports, "__esModule", {
  160. value: true
  161. });
  162. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  163. exports.default = isByteLength;
  164. var _assertString = assertString_1;
  165. var _assertString2 = _interopRequireDefault(_assertString);
  166. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  167. /* eslint-disable prefer-rest-params */
  168. function isByteLength(str, options) {
  169. (0, _assertString2.default)(str);
  170. var min = void 0;
  171. var max = void 0;
  172. if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
  173. min = options.min || 0;
  174. max = options.max;
  175. } else {
  176. // backwards compatibility: isByteLength(str, min [, max])
  177. min = arguments[1];
  178. max = arguments[2];
  179. }
  180. var len = encodeURI(str).split(/%..|./).length - 1;
  181. return len >= min && (typeof max === 'undefined' || len <= max);
  182. }
  183. module.exports = exports['default'];
  184. });
  185. var isFQDN = createCommonjsModule(function (module, exports) {
  186. 'use strict';
  187. Object.defineProperty(exports, "__esModule", {
  188. value: true
  189. });
  190. exports.default = isFDQN;
  191. var _assertString = assertString_1;
  192. var _assertString2 = _interopRequireDefault(_assertString);
  193. var _merge = merge_1;
  194. var _merge2 = _interopRequireDefault(_merge);
  195. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  196. var default_fqdn_options = {
  197. require_tld: true,
  198. allow_underscores: false,
  199. allow_trailing_dot: false
  200. };
  201. function isFDQN(str, options) {
  202. (0, _assertString2.default)(str);
  203. options = (0, _merge2.default)(options, default_fqdn_options);
  204. /* Remove the optional trailing dot before checking validity */
  205. if (options.allow_trailing_dot && str[str.length - 1] === '.') {
  206. str = str.substring(0, str.length - 1);
  207. }
  208. var parts = str.split('.');
  209. if (options.require_tld) {
  210. var tld = parts.pop();
  211. if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
  212. return false;
  213. }
  214. }
  215. for (var part, i = 0; i < parts.length; i++) {
  216. part = parts[i];
  217. if (options.allow_underscores) {
  218. part = part.replace(/_/g, '');
  219. }
  220. if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) {
  221. return false;
  222. }
  223. if (/[\uff01-\uff5e]/.test(part)) {
  224. // disallow full-width chars
  225. return false;
  226. }
  227. if (part[0] === '-' || part[part.length - 1] === '-') {
  228. return false;
  229. }
  230. }
  231. return true;
  232. }
  233. module.exports = exports['default'];
  234. });
  235. var isEmail_1 = createCommonjsModule(function (module, exports) {
  236. 'use strict';
  237. Object.defineProperty(exports, "__esModule", {
  238. value: true
  239. });
  240. exports.default = isEmail;
  241. var _assertString = assertString_1;
  242. var _assertString2 = _interopRequireDefault(_assertString);
  243. var _merge = merge_1;
  244. var _merge2 = _interopRequireDefault(_merge);
  245. var _isByteLength = isByteLength_1;
  246. var _isByteLength2 = _interopRequireDefault(_isByteLength);
  247. var _isFQDN = isFQDN;
  248. var _isFQDN2 = _interopRequireDefault(_isFQDN);
  249. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  250. var default_email_options = {
  251. allow_display_name: false,
  252. allow_utf8_local_part: true,
  253. require_tld: true
  254. };
  255. /* eslint-disable max-len */
  256. /* eslint-disable no-control-regex */
  257. var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i;
  258. var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i;
  259. var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i;
  260. var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i;
  261. var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i;
  262. /* eslint-enable max-len */
  263. /* eslint-enable no-control-regex */
  264. function isEmail(str, options) {
  265. (0, _assertString2.default)(str);
  266. options = (0, _merge2.default)(options, default_email_options);
  267. if (options.allow_display_name) {
  268. var display_email = str.match(displayName);
  269. if (display_email) {
  270. str = display_email[1];
  271. }
  272. }
  273. var parts = str.split('@');
  274. var domain = parts.pop();
  275. var user = parts.join('@');
  276. var lower_domain = domain.toLowerCase();
  277. if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') {
  278. user = user.replace(/\./g, '').toLowerCase();
  279. }
  280. if (!(0, _isByteLength2.default)(user, { max: 64 }) || !(0, _isByteLength2.default)(domain, { max: 256 })) {
  281. return false;
  282. }
  283. if (!(0, _isFQDN2.default)(domain, { require_tld: options.require_tld })) {
  284. return false;
  285. }
  286. if (user[0] === '"') {
  287. user = user.slice(1, user.length - 1);
  288. return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
  289. }
  290. var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
  291. var user_parts = user.split('.');
  292. for (var i = 0; i < user_parts.length; i++) {
  293. if (!pattern.test(user_parts[i])) {
  294. return false;
  295. }
  296. }
  297. return true;
  298. }
  299. module.exports = exports['default'];
  300. });
  301. var isEmail = unwrapExports(isEmail_1);
  302. var email = function (value) { return isEmail(String(value)); };
  303. var ext = function (files, extensions) {
  304. var regex = new RegExp((".(" + (extensions.join('|')) + ")$"), 'i');
  305. return files.every(function (file) { return regex.test(file.name); });
  306. };
  307. var image = function (files) { return files.every(function (file) { return /\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(file.name); }
  308. ); };
  309. var In = function (value, options) { return !! options.filter(function (option) { return option == value; }).length; }; // eslint-disable-line
  310. var isIP_1 = createCommonjsModule(function (module, exports) {
  311. 'use strict';
  312. Object.defineProperty(exports, "__esModule", {
  313. value: true
  314. });
  315. exports.default = isIP;
  316. var _assertString = assertString_1;
  317. var _assertString2 = _interopRequireDefault(_assertString);
  318. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  319. var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
  320. var ipv6Block = /^[0-9A-F]{1,4}$/i;
  321. function isIP(str) {
  322. var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  323. (0, _assertString2.default)(str);
  324. version = String(version);
  325. if (!version) {
  326. return isIP(str, 4) || isIP(str, 6);
  327. } else if (version === '4') {
  328. if (!ipv4Maybe.test(str)) {
  329. return false;
  330. }
  331. var parts = str.split('.').sort(function (a, b) {
  332. return a - b;
  333. });
  334. return parts[3] <= 255;
  335. } else if (version === '6') {
  336. var blocks = str.split(':');
  337. var foundOmissionBlock = false; // marker to indicate ::
  338. // At least some OS accept the last 32 bits of an IPv6 address
  339. // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
  340. // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
  341. // and '::a.b.c.d' is deprecated, but also valid.
  342. var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);
  343. var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;
  344. if (blocks.length > expectedNumberOfBlocks) {
  345. return false;
  346. }
  347. // initial or final ::
  348. if (str === '::') {
  349. return true;
  350. } else if (str.substr(0, 2) === '::') {
  351. blocks.shift();
  352. blocks.shift();
  353. foundOmissionBlock = true;
  354. } else if (str.substr(str.length - 2) === '::') {
  355. blocks.pop();
  356. blocks.pop();
  357. foundOmissionBlock = true;
  358. }
  359. for (var i = 0; i < blocks.length; ++i) {
  360. // test for a :: which can not be at the string start/end
  361. // since those cases have been handled above
  362. if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {
  363. if (foundOmissionBlock) {
  364. return false; // multiple :: in address
  365. }
  366. foundOmissionBlock = true;
  367. } else if (foundIPv4TransitionBlock && i === blocks.length - 1) {
  368. // it has been checked before that the last
  369. // block is a valid IPv4 address
  370. } else if (!ipv6Block.test(blocks[i])) {
  371. return false;
  372. }
  373. }
  374. if (foundOmissionBlock) {
  375. return blocks.length >= 1;
  376. }
  377. return blocks.length === expectedNumberOfBlocks;
  378. }
  379. return false;
  380. }
  381. module.exports = exports['default'];
  382. });
  383. var isIP = unwrapExports(isIP_1);
  384. var ip = function (value, ref) {
  385. if ( ref === void 0 ) ref = [4];
  386. var version = ref[0];
  387. return isIP(value, version);
  388. };
  389. var max = function (value, ref) {
  390. var length = ref[0];
  391. if (value === undefined || value === null) {
  392. return length >= 0;
  393. }
  394. return String(value).length <= length;
  395. };
  396. var max_value = function (value, ref) {
  397. var max = ref[0];
  398. if (Array.isArray(value) || value === null || value === undefined || value === '') {
  399. return false;
  400. }
  401. return Number(value) <= max;
  402. };
  403. var mimes = function (files, mimes) {
  404. var regex = new RegExp(((mimes.join('|').replace('*', '.+')) + "$"), 'i');
  405. return files.every(function (file) { return regex.test(file.type); });
  406. };
  407. var min = function (value, ref) {
  408. var length = ref[0];
  409. if (value === undefined || value === null) {
  410. return false;
  411. }
  412. return String(value).length >= length;
  413. };
  414. var min_value = function (value, ref) {
  415. var min = ref[0];
  416. if (Array.isArray(value) || value === null || value === undefined || value === '') {
  417. return false;
  418. }
  419. return Number(value) >= min;
  420. };
  421. var not_in = function (value, options) { return ! options.filter(function (option) { return option == value; }).length; }; // eslint-disable-line
  422. var numeric = function (value) { return /^[0-9]+$/.test(String(value)); };
  423. var regex = function (value, ref) {
  424. var regex = ref[0];
  425. var flags = ref.slice(1);
  426. if (regex instanceof RegExp) {
  427. return regex.test(value);
  428. }
  429. return new RegExp(regex, flags).test(String(value));
  430. };
  431. var required = function (value) {
  432. if (Array.isArray(value)) {
  433. return !! value.length;
  434. }
  435. if (value === undefined || value === null) {
  436. return false;
  437. }
  438. return !! String(value).trim().length;
  439. };
  440. var size = function (files, ref) {
  441. var size = ref[0];
  442. if (isNaN(size)) {
  443. return false;
  444. }
  445. var nSize = Number(size) * 1024;
  446. for (var i = 0; i < files.length; i++) {
  447. if (files[i].size > nSize) {
  448. return false;
  449. }
  450. }
  451. return true;
  452. };
  453. var isURL_1 = createCommonjsModule(function (module, exports) {
  454. 'use strict';
  455. Object.defineProperty(exports, "__esModule", {
  456. value: true
  457. });
  458. exports.default = isURL;
  459. var _assertString = assertString_1;
  460. var _assertString2 = _interopRequireDefault(_assertString);
  461. var _isFQDN = isFQDN;
  462. var _isFQDN2 = _interopRequireDefault(_isFQDN);
  463. var _isIP = isIP_1;
  464. var _isIP2 = _interopRequireDefault(_isIP);
  465. var _merge = merge_1;
  466. var _merge2 = _interopRequireDefault(_merge);
  467. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  468. var default_url_options = {
  469. protocols: ['http', 'https', 'ftp'],
  470. require_tld: true,
  471. require_protocol: false,
  472. require_host: true,
  473. require_valid_protocol: true,
  474. allow_underscores: false,
  475. allow_trailing_dot: false,
  476. allow_protocol_relative_urls: false
  477. };
  478. var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/;
  479. function isRegExp(obj) {
  480. return Object.prototype.toString.call(obj) === '[object RegExp]';
  481. }
  482. function checkHost(host, matches) {
  483. for (var i = 0; i < matches.length; i++) {
  484. var match = matches[i];
  485. if (host === match || isRegExp(match) && match.test(host)) {
  486. return true;
  487. }
  488. }
  489. return false;
  490. }
  491. function isURL(url, options) {
  492. (0, _assertString2.default)(url);
  493. if (!url || url.length >= 2083 || /\s/.test(url)) {
  494. return false;
  495. }
  496. if (url.indexOf('mailto:') === 0) {
  497. return false;
  498. }
  499. options = (0, _merge2.default)(options, default_url_options);
  500. var protocol = void 0,
  501. auth = void 0,
  502. host = void 0,
  503. hostname = void 0,
  504. port = void 0,
  505. port_str = void 0,
  506. split = void 0,
  507. ipv6 = void 0;
  508. split = url.split('#');
  509. url = split.shift();
  510. split = url.split('?');
  511. url = split.shift();
  512. split = url.split('://');
  513. if (split.length > 1) {
  514. protocol = split.shift();
  515. if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
  516. return false;
  517. }
  518. } else if (options.require_protocol) {
  519. return false;
  520. } else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') {
  521. split[0] = url.substr(2);
  522. }
  523. url = split.join('://');
  524. split = url.split('/');
  525. url = split.shift();
  526. if (url === '' && !options.require_host) {
  527. return true;
  528. }
  529. split = url.split('@');
  530. if (split.length > 1) {
  531. auth = split.shift();
  532. if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
  533. return false;
  534. }
  535. }
  536. hostname = split.join('@');
  537. port_str = ipv6 = null;
  538. var ipv6_match = hostname.match(wrapped_ipv6);
  539. if (ipv6_match) {
  540. host = '';
  541. ipv6 = ipv6_match[1];
  542. port_str = ipv6_match[2] || null;
  543. } else {
  544. split = hostname.split(':');
  545. host = split.shift();
  546. if (split.length) {
  547. port_str = split.join(':');
  548. }
  549. }
  550. if (port_str !== null) {
  551. port = parseInt(port_str, 10);
  552. if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
  553. return false;
  554. }
  555. }
  556. if (!(0, _isIP2.default)(host) && !(0, _isFQDN2.default)(host, options) && (!ipv6 || !(0, _isIP2.default)(ipv6, 6)) && host !== 'localhost') {
  557. return false;
  558. }
  559. host = host || ipv6;
  560. if (options.host_whitelist && !checkHost(host, options.host_whitelist)) {
  561. return false;
  562. }
  563. if (options.host_blacklist && checkHost(host, options.host_blacklist)) {
  564. return false;
  565. }
  566. return true;
  567. }
  568. module.exports = exports['default'];
  569. });
  570. var isURL = unwrapExports(isURL_1);
  571. var url = function (value, ref) {
  572. if ( ref === void 0 ) ref = [true];
  573. var requireProtocol = ref[0];
  574. return isURL(value, { require_protocol: !! requireProtocol });
  575. };
  576. /* eslint-disable camelcase */
  577. var Rules = {
  578. alpha_dash: alpha_dash,
  579. alpha_num: alpha_num,
  580. alpha_spaces: alpha_spaces,
  581. alpha: alpha,
  582. between: between,
  583. confirmed: confirmed,
  584. credit_card: credit_card,
  585. decimal: decimal,
  586. digits: digits,
  587. dimensions: dimensions,
  588. email: email,
  589. ext: ext,
  590. image: image,
  591. in: In,
  592. ip: ip,
  593. max: max,
  594. max_value: max_value,
  595. mimes: mimes,
  596. min: min,
  597. min_value: min_value,
  598. not_in: not_in,
  599. numeric: numeric,
  600. regex: regex,
  601. required: required,
  602. size: size,
  603. url: url
  604. };
  605. var ErrorBag = function ErrorBag() {
  606. this.errors = [];
  607. };
  608. /**
  609. * Adds an error to the internal array.
  610. *
  611. * @param {string} field The field name.
  612. * @param {string} msg The error message.
  613. * @param {String} rule The rule that is responsible for the error.
  614. * @param {String} scope The Scope name, optional.
  615. */
  616. ErrorBag.prototype.add = function add (field, msg, rule, scope) {
  617. if ( scope === void 0 ) scope = '__global__';
  618. this.errors.push({ field: field, msg: msg, rule: rule, scope: scope });
  619. };
  620. /**
  621. * Gets all error messages from the internal array.
  622. *
  623. * @param {String} scope The Scope name, optional.
  624. * @return {Array} errors Array of all error messages.
  625. */
  626. ErrorBag.prototype.all = function all (scope) {
  627. if (! scope) {
  628. return this.errors.map(function (e) { return e.msg; });
  629. }
  630. return this.errors.filter(function (e) { return e.scope === scope; }).map(function (e) { return e.msg; });
  631. };
  632. /**
  633. * Checks if there are any errors in the internal array.
  634. * @param {String} scope The Scope name, optional.
  635. * @return {boolean} result True if there was at least one error, false otherwise.
  636. */
  637. ErrorBag.prototype.any = function any (scope) {
  638. if (! scope) {
  639. return !! this.errors.length;
  640. }
  641. return !! this.errors.filter(function (e) { return e.scope === scope; }).length;
  642. };
  643. /**
  644. * Removes all items from the internal array.
  645. *
  646. * @param {String} scope The Scope name, optional.
  647. */
  648. ErrorBag.prototype.clear = function clear (scope) {
  649. if (! scope) {
  650. scope = '__global__';
  651. }
  652. this.errors = this.errors.filter(function (e) { return e.scope !== scope; });
  653. };
  654. /**
  655. * Collects errors into groups or for a specific field.
  656. *
  657. * @param{string} field The field name.
  658. * @param{string} scope The scope name.
  659. * @param {Boolean} map If it should map the errors to strings instead of objects.
  660. * @return {Array} errors The errors for the specified field.
  661. */
  662. ErrorBag.prototype.collect = function collect (field, scope, map) {
  663. if ( map === void 0 ) map = true;
  664. if (! field) {
  665. var collection = {};
  666. this.errors.forEach(function (e) {
  667. if (! collection[e.field]) {
  668. collection[e.field] = [];
  669. }
  670. collection[e.field].push(map ? e.msg : e);
  671. });
  672. return collection;
  673. }
  674. if (scope) {
  675. return this.errors.filter(function (e) { return e.field === field && e.scope === scope; })
  676. .map(function (e) { return (map ? e.msg : e); });
  677. }
  678. return this.errors.filter(function (e) { return e.field === field && e.scope === '__global__'; })
  679. .map(function (e) { return (map ? e.msg : e); });
  680. };
  681. /**
  682. * Gets the internal array length.
  683. *
  684. * @return {Number} length The internal array length.
  685. */
  686. ErrorBag.prototype.count = function count () {
  687. return this.errors.length;
  688. };
  689. /**
  690. * Gets the first error message for a specific field.
  691. *
  692. * @param{string} field The field name.
  693. * @return {string|null} message The error message.
  694. */
  695. ErrorBag.prototype.first = function first (field, scope) {
  696. var this$1 = this;
  697. if ( scope === void 0 ) scope = '__global__';
  698. var selector = this._selector(field);
  699. var scoped = this._scope(field);
  700. if (scoped) {
  701. var result = this.first(scoped.name, scoped.scope);
  702. // if such result exist, return it. otherwise it could be a field.
  703. // with dot in its name.
  704. if (result) {
  705. return result;
  706. }
  707. }
  708. if (selector) {
  709. return this.firstByRule(selector.name, selector.rule, scope);
  710. }
  711. for (var i = 0; i < this.errors.length; i++) {
  712. if (this$1.errors[i].field === field && (this$1.errors[i].scope === scope)) {
  713. return this$1.errors[i].msg;
  714. }
  715. }
  716. return null;
  717. };
  718. /**
  719. * Returns the first error rule for the specified field
  720. *
  721. * @param {string} field The specified field.
  722. * @return {string|null} First error rule on the specified field if one is found, otherwise null
  723. */
  724. ErrorBag.prototype.firstRule = function firstRule (field, scope) {
  725. var errors = this.collect(field, scope, false);
  726. return (errors.length && errors[0].rule) || null;
  727. };
  728. /**
  729. * Checks if the internal array has at least one error for the specified field.
  730. *
  731. * @param{string} field The specified field.
  732. * @return {Boolean} result True if at least one error is found, false otherwise.
  733. */
  734. ErrorBag.prototype.has = function has (field, scope) {
  735. if ( scope === void 0 ) scope = '__global__';
  736. return !! this.first(field, scope);
  737. };
  738. /**
  739. * Gets the first error message for a specific field and a rule.
  740. * @param {String} name The name of the field.
  741. * @param {String} rule The name of the rule.
  742. * @param {String} scope The name of the scope (optional).
  743. */
  744. ErrorBag.prototype.firstByRule = function firstByRule (name, rule, scope) {
  745. var error = this.collect(name, scope, false).filter(function (e) { return e.rule === rule; })[0];
  746. return (error && error.msg) || null;
  747. };
  748. /**
  749. * Removes all error messages associated with a specific field.
  750. *
  751. * @param{string} field The field which messages are to be removed.
  752. * @param {String} scope The Scope name, optional.
  753. */
  754. ErrorBag.prototype.remove = function remove (field, scope) {
  755. if (scope) {
  756. this.errors = this.errors.filter(function (e) { return e.field !== field || e.scope !== scope; });
  757. return;
  758. }
  759. this.errors = this.errors.filter(function (e) { return e.field !== field && e.scope === '__global__'; });
  760. };
  761. /**
  762. * Get the field attributes if there's a rule selector.
  763. *
  764. * @param{string} field The specified field.
  765. * @return {Object|null}
  766. */
  767. ErrorBag.prototype._selector = function _selector (field) {
  768. if (field.indexOf(':') > -1) {
  769. var ref = field.split(':');
  770. var name = ref[0];
  771. var rule = ref[1];
  772. return { name: name, rule: rule };
  773. }
  774. return null;
  775. };
  776. /**
  777. * Get the field scope if specified using dot notation.
  778. *
  779. * @param {string} field the specifie field.
  780. * @return {Object|null}
  781. */
  782. ErrorBag.prototype._scope = function _scope (field) {
  783. if (field.indexOf('.') > -1) {
  784. var ref = field.split('.');
  785. var scope = ref[0];
  786. var name = ref[1];
  787. return { name: name, scope: scope };
  788. }
  789. return null;
  790. };
  791. var ValidatorException = (function () {
  792. function anonymous(msg) {
  793. this.msg = "[vee-validate]: " + msg;
  794. }
  795. anonymous.prototype.toString = function toString () {
  796. return this.msg;
  797. };
  798. return anonymous;
  799. }());
  800. /**
  801. * Gets the data attribute. the name must be kebab-case.
  802. */
  803. var getDataAttribute = function (el, name) { return el.getAttribute(("data-vv-" + name)); };
  804. /**
  805. * Determines the input field scope.
  806. */
  807. var getScope = function (el) {
  808. var scope = getDataAttribute(el, 'scope');
  809. if (! scope && el.form) {
  810. scope = getDataAttribute(el.form, 'scope');
  811. }
  812. return scope;
  813. };
  814. /**
  815. * Debounces a function.
  816. */
  817. var debounce = function (callback, wait, immediate) {
  818. if ( wait === void 0 ) wait = 0;
  819. var timeout;
  820. if (wait == 0) {
  821. return callback;
  822. }
  823. return function () {
  824. var args = [], len = arguments.length;
  825. while ( len-- ) args[ len ] = arguments[ len ];
  826. var later = function () {
  827. timeout = null;
  828. if (!immediate) { callback.apply(void 0, args); }
  829. };
  830. var callNow = immediate && !timeout;
  831. clearTimeout(timeout);
  832. timeout = setTimeout(later, wait);
  833. if (callNow) { callback(args); }
  834. };
  835. };
  836. /**
  837. * Emits a warning to the console.
  838. */
  839. var warn = function (message) {
  840. if (! console) {
  841. return;
  842. }
  843. console.warn(("[vee-validate]: " + message)); // eslint-disable-line
  844. };
  845. /**
  846. * Checks if the value is an object.
  847. */
  848. var isObject = function (object) {
  849. return object !== null && object && typeof object === 'object' && ! Array.isArray(object);
  850. };
  851. /**
  852. * Checks if a function is callable.
  853. */
  854. var isCallable = function (func) { return typeof func === 'function'; };
  855. /**
  856. * Check if element has the css class on it.
  857. */
  858. var hasClass = function (el, className) {
  859. if (el.classList) {
  860. return el.classList.contains(className);
  861. }
  862. return !!el.className.match(new RegExp(("(\\s|^)" + className + "(\\s|$)")));
  863. };
  864. /**
  865. * Adds the provided css className to the element.
  866. */
  867. var addClass = function (el, className) {
  868. if (el.classList) {
  869. el.classList.add(className);
  870. return;
  871. }
  872. if (!hasClass(el, className)) {
  873. el.className += " " + className;
  874. }
  875. };
  876. /**
  877. * Remove the provided css className from the element.
  878. */
  879. var removeClass = function (el, className) {
  880. if (el.classList) {
  881. el.classList.remove(className);
  882. return;
  883. }
  884. if (hasClass(el, className)) {
  885. var reg = new RegExp(("(\\s|^)" + className + "(\\s|$)"));
  886. el.className = el.className.replace(reg, ' ');
  887. }
  888. };
  889. /**
  890. * Converts an array-like object to array.
  891. * Simple polyfill for Array.from
  892. */
  893. var toArray = function (arrayLike) {
  894. if (Array.from) {
  895. return Array.from(arrayLike);
  896. }
  897. var array = [];
  898. var length = arrayLike.length;
  899. for (var i = 0; i < length; i++) {
  900. array.push(arrayLike[i]);
  901. }
  902. return array;
  903. };
  904. /**
  905. * Assign polyfill from the mdn.
  906. */
  907. var assign = function (target) {
  908. var others = [], len = arguments.length - 1;
  909. while ( len-- > 0 ) others[ len ] = arguments[ len + 1 ];
  910. if (Object.assign) {
  911. return Object.assign.apply(Object, [ target ].concat( others ));
  912. }
  913. if (target == null) {
  914. throw new TypeError('Cannot convert undefined or null to object');
  915. }
  916. var to = Object(target);
  917. others.forEach(function (arg) {
  918. // Skip over if undefined or null
  919. if (arg != null) {
  920. Object.keys(arg).forEach(function (key) {
  921. to[key] = arg[key];
  922. });
  923. }
  924. });
  925. return to;
  926. };
  927. /**
  928. * polyfills array.find
  929. * @param {Array} array
  930. * @param {Function} predicate
  931. */
  932. var find = function (array, predicate) {
  933. if (array.find) {
  934. return array.find(predicate);
  935. }
  936. var result;
  937. array.some(function (item) {
  938. if (predicate(item)) {
  939. result = item;
  940. return true;
  941. }
  942. return false;
  943. });
  944. return result;
  945. };
  946. /**
  947. * Gets the rules from a binding value or the element dataset.
  948. *
  949. * @param {String} expression The binding expression.
  950. * @param {Object|String} value The binding value.
  951. * @param {element} el The element.
  952. * @returns {String|Object}
  953. */
  954. var getRules = function (expression, value, el) {
  955. if (! expression) {
  956. return getDataAttribute(el, 'rules');
  957. }
  958. if (typeof value === 'string') {
  959. return value;
  960. }
  961. if (~['string', 'object'].indexOf(typeof value.rules)) {
  962. return value.rules
  963. }
  964. return value;
  965. };
  966. /* eslint-disable prefer-rest-params */
  967. var Dictionary = function Dictionary(dictionary) {
  968. if ( dictionary === void 0 ) dictionary = {};
  969. this.dictionary = {};
  970. this.merge(dictionary);
  971. };
  972. Dictionary.prototype.hasLocale = function hasLocale (locale) {
  973. return !! this.dictionary[locale];
  974. };
  975. Dictionary.prototype.getMessage = function getMessage (locale, key, fallback) {
  976. if (! this.hasMessage(locale, key)) {
  977. return fallback || this._getDefaultMessage(locale);
  978. }
  979. return this.dictionary[locale].messages[key];
  980. };
  981. Dictionary.prototype._getDefaultMessage = function _getDefaultMessage (locale) {
  982. if (this.hasMessage(locale, '_default')) {
  983. return this.dictionary[locale].messages._default;
  984. }
  985. return this.dictionary.en.messages._default;
  986. };
  987. Dictionary.prototype.getAttribute = function getAttribute (locale, key, fallback) {
  988. if ( fallback === void 0 ) fallback = '';
  989. if (! this.hasAttribute(locale, key)) {
  990. return fallback;
  991. }
  992. return this.dictionary[locale].attributes[key];
  993. };
  994. Dictionary.prototype.hasMessage = function hasMessage (locale, key) {
  995. return !! (
  996. this.hasLocale(locale) &&
  997. this.dictionary[locale].messages &&
  998. this.dictionary[locale].messages[key]
  999. );
  1000. };
  1001. Dictionary.prototype.hasAttribute = function hasAttribute (locale, key) {
  1002. return !! (
  1003. this.hasLocale(locale) &&
  1004. this.dictionary[locale].attributes &&
  1005. this.dictionary[locale].attributes[key]
  1006. );
  1007. };
  1008. Dictionary.prototype.merge = function merge (dictionary) {
  1009. this._merge(this.dictionary, dictionary);
  1010. };
  1011. Dictionary.prototype.setMessage = function setMessage (locale, key, message) {
  1012. if (! this.hasLocale(locale)) {
  1013. this.dictionary[locale] = {
  1014. messages: {},
  1015. attributes: {}
  1016. };
  1017. }
  1018. this.dictionary[locale].messages[key] = message;
  1019. };
  1020. Dictionary.prototype.setAttribute = function setAttribute (locale, key, attribute) {
  1021. if (! this.hasLocale(locale)) {
  1022. this.dictionary[locale] = {
  1023. messages: {},
  1024. attributes: {}
  1025. };
  1026. }
  1027. this.dictionary[locale].attributes[key] = attribute;
  1028. };
  1029. Dictionary.prototype._merge = function _merge (target, source) {
  1030. var this$1 = this;
  1031. if (! (isObject(target) && isObject(source))) {
  1032. return target;
  1033. }
  1034. Object.keys(source).forEach(function (key) {
  1035. if (isObject(source[key])) {
  1036. if (! target[key]) {
  1037. assign(target, ( obj = {}, obj[key] = {}, obj ));
  1038. var obj;
  1039. }
  1040. this$1._merge(target[key], source[key]);
  1041. return;
  1042. }
  1043. assign(target, ( obj$1 = {}, obj$1[key] = source[key], obj$1 ));
  1044. var obj$1;
  1045. });
  1046. return target;
  1047. };
  1048. /* istanbul ignore next */
  1049. /* eslint-disable max-len */
  1050. var messages = {
  1051. _default: function (field) { return ("The " + field + " value is not valid."); },
  1052. alpha_dash: function (field) { return ("The " + field + " field may contain alpha-numeric characters as well as dashes and underscores."); },
  1053. alpha_num: function (field) { return ("The " + field + " field may only contain alpha-numeric characters."); },
  1054. alpha_spaces: function (field) { return ("The " + field + " field may only contain alphabetic characters as well as spaces."); },
  1055. alpha: function (field) { return ("The " + field + " field may only contain alphabetic characters."); },
  1056. between: function (field, ref) {
  1057. var min = ref[0];
  1058. var max = ref[1];
  1059. return ("The " + field + " field must be between " + min + " and " + max + ".");
  1060. },
  1061. confirmed: function (field) { return ("The " + field + " confirmation does not match."); },
  1062. credit_card: function (field) { return ("The " + field + " field is invalid."); },
  1063. decimal: function (field, ref) {
  1064. if ( ref === void 0 ) ref = ['*'];
  1065. var decimals = ref[0];
  1066. return ("The " + field + " field must be numeric and may contain " + (decimals === '*' ? '' : decimals) + " decimal points.");
  1067. },
  1068. digits: function (field, ref) {
  1069. var length = ref[0];
  1070. return ("The " + field + " field must be numeric and exactly contain " + length + " digits.");
  1071. },
  1072. dimensions: function (field, ref) {
  1073. var width = ref[0];
  1074. var height = ref[1];
  1075. return ("The " + field + " field must be " + width + " pixels by " + height + " pixels.");
  1076. },
  1077. email: function (field) { return ("The " + field + " field must be a valid email."); },
  1078. ext: function (field) { return ("The " + field + " field must be a valid file."); },
  1079. image: function (field) { return ("The " + field + " field must be an image."); },
  1080. in: function (field) { return ("The " + field + " field must be a valid value."); },
  1081. ip: function (field) { return ("The " + field + " field must be a valid ip address."); },
  1082. max: function (field, ref) {
  1083. var length = ref[0];
  1084. return ("The " + field + " field may not be greater than " + length + " characters.");
  1085. },
  1086. max_value: function (field, ref) {
  1087. var max = ref[0];
  1088. return ("The " + field + " field must be " + max + " or less.");
  1089. },
  1090. mimes: function (field) { return ("The " + field + " field must have a valid file type."); },
  1091. min: function (field, ref) {
  1092. var length = ref[0];
  1093. return ("The " + field + " field must be at least " + length + " characters.");
  1094. },
  1095. min_value: function (field, ref) {
  1096. var min = ref[0];
  1097. return ("The " + field + " field must be " + min + " or more.");
  1098. },
  1099. not_in: function (field) { return ("The " + field + " field must be a valid value."); },
  1100. numeric: function (field) { return ("The " + field + " field may only contain numeric characters."); },
  1101. regex: function (field) { return ("The " + field + " field format is invalid."); },
  1102. required: function (field) { return ("The " + field + " field is required."); },
  1103. size: function (field, ref) {
  1104. var size = ref[0];
  1105. return ("The " + field + " field must be less than " + size + " KB.");
  1106. },
  1107. url: function (field) { return ("The " + field + " field is not a valid URL."); }
  1108. };
  1109. var after = function (moment) { return function (value, ref) {
  1110. var targetField = ref[0];
  1111. var format = ref[1];
  1112. var dateValue = moment(value, format, true);
  1113. var field = document.querySelector(("input[name='" + targetField + "']"));
  1114. if (! (dateValue.isValid() && field)) {
  1115. return false;
  1116. }
  1117. var other = moment(field.value, format, true);
  1118. if (! other.isValid()) {
  1119. return false;
  1120. }
  1121. return dateValue.isAfter(other);
  1122. }; };
  1123. var before = function (moment) { return function (value, ref) {
  1124. var targetField = ref[0];
  1125. var format = ref[1];
  1126. var dateValue = moment(value, format, true);
  1127. var field = document.querySelector(("input[name='" + targetField + "']"));
  1128. if (! dateValue.isValid() || ! field) {
  1129. return false;
  1130. }
  1131. var other = moment(field.value, format, true);
  1132. if (! other.isValid()) {
  1133. return false;
  1134. }
  1135. return dateValue.isBefore(other);
  1136. }; };
  1137. var date_format = function (moment) { return function (value, ref) {
  1138. var format = ref[0];
  1139. return moment(value, format, true).isValid();
  1140. } };
  1141. var date_between = function (moment) { return function (value, ref) {
  1142. var min = ref[0];
  1143. var max = ref[1];
  1144. var format = ref[2];
  1145. var minDate = moment(min, format, true);
  1146. var maxDate = moment(max, format, true);
  1147. var dateVal = moment(value, format, true);
  1148. if (! (minDate.isValid() && maxDate.isValid() && dateVal.isValid())) {
  1149. return false;
  1150. }
  1151. return dateVal.isBetween(minDate, maxDate);
  1152. }; };
  1153. /* istanbul ignore next */
  1154. /* eslint-disable max-len */
  1155. var messages$1 = {
  1156. after: function (field, ref) {
  1157. var target = ref[0];
  1158. return ("The " + field + " must be after " + target + ".");
  1159. },
  1160. before: function (field, ref) {
  1161. var target = ref[0];
  1162. return ("The " + field + " must be before " + target + ".");
  1163. },
  1164. date_between: function (field, ref) {
  1165. var min = ref[0];
  1166. var max = ref[1];
  1167. return ("The " + field + " must be between " + min + " and " + max + ".");
  1168. },
  1169. date_format: function (field, ref) {
  1170. var format = ref[0];
  1171. return ("The " + field + " must be in the format " + format + ".");
  1172. }
  1173. };
  1174. var date = {
  1175. make: function (moment) { return ({
  1176. date_format: date_format(moment),
  1177. after: after(moment),
  1178. before: before(moment),
  1179. date_between: date_between(moment)
  1180. }); },
  1181. messages: messages$1,
  1182. installed: false
  1183. };
  1184. var FieldBag = function FieldBag() {
  1185. this.fields = {};
  1186. };
  1187. /**
  1188. * Initializes and adds a new field to the bag.
  1189. */
  1190. FieldBag.prototype._add = function _add (name) {
  1191. this.fields[name] = {};
  1192. this._setFlags(name, { dirty: false, valid: false, }, true);
  1193. };
  1194. /**
  1195. * Adds a field if it does not exist.
  1196. */
  1197. FieldBag.prototype._addIfNotExists = function _addIfNotExists (name) {
  1198. if (this.fields[name]) {
  1199. return;
  1200. }
  1201. this._add(name);
  1202. };
  1203. /**
  1204. * Remooves a field from the bag.
  1205. */
  1206. FieldBag.prototype._remove = function _remove (name) {
  1207. delete this.fields[name];
  1208. };
  1209. /**
  1210. * Resets the flags state for a specified field or all fields.
  1211. */
  1212. FieldBag.prototype.reset = function reset (name) {
  1213. var this$1 = this;
  1214. if (! name) {
  1215. Object.keys(this.fields).forEach(function (field) {
  1216. this$1._setFlags(field, { dirty: false, valid: false, }, true);
  1217. });
  1218. return;
  1219. }
  1220. this._setFlags(name, { dirty: false, valid: false, }, true);
  1221. };
  1222. /**
  1223. * Sets the flags for a specified field.
  1224. */
  1225. FieldBag.prototype._setFlags = function _setFlags (name, flags, initial) {
  1226. var this$1 = this;
  1227. if ( initial === void 0 ) initial = false;
  1228. return Object.keys(flags).every(
  1229. function (flag) { return this$1._setFlag(name, flag, flags[flag], initial); }
  1230. );
  1231. };
  1232. /**
  1233. * Sets a flag for a specified field.
  1234. */
  1235. FieldBag.prototype._setFlag = function _setFlag (name, flag, value, initial) {
  1236. if ( initial === void 0 ) initial = false;
  1237. var method = "set" + (flag.charAt(0).toUpperCase()) + (flag.slice(1));
  1238. if (typeof this[method] !== 'function') {
  1239. return false;
  1240. }
  1241. this[method](name, value, initial);
  1242. return true;
  1243. };
  1244. /**
  1245. * Sets the dirty flag along with dependant flags.
  1246. */
  1247. FieldBag.prototype.setDirty = function setDirty (name, value, initial) {
  1248. if ( initial === void 0 ) initial = false;
  1249. this.fields[name].dirty = value;
  1250. this.fields[name].clean = initial || ! value;
  1251. this.fields[name].passed = this.fields[name].valid && value;
  1252. this.fields[name].failed = ! this.fields[name].valid && value;
  1253. };
  1254. /**
  1255. * Sets the valid flag along with dependant flags.
  1256. */
  1257. FieldBag.prototype.setValid = function setValid (name, value) {
  1258. this.fields[name].valid = value;
  1259. this.fields[name].passed = this.fields[name].dirty && value;
  1260. this.fields[name].failed = this.fields[name].dirty && ! value;
  1261. };
  1262. /**
  1263. * Gets a field flag value.
  1264. */
  1265. FieldBag.prototype._getFieldFlag = function _getFieldFlag (name, flag) {
  1266. if (this.fields[name]) {
  1267. return this.fields[name][flag];
  1268. }
  1269. return false;
  1270. };
  1271. FieldBag.prototype.dirty = function dirty (name) {
  1272. var this$1 = this;
  1273. if (! name) {
  1274. return Object.keys(this.fields).some(function (field) { return this$1.fields[field].dirty; });
  1275. }
  1276. return this._getFieldFlag(name, 'dirty');
  1277. };
  1278. FieldBag.prototype.valid = function valid (name) {
  1279. var this$1 = this;
  1280. if (! name) {
  1281. return Object.keys(this.fields).every(function (field) { return this$1.fields[field].valid; });
  1282. }
  1283. return this._getFieldFlag(name, 'valid');
  1284. };
  1285. FieldBag.prototype.passed = function passed (name) {
  1286. var this$1 = this;
  1287. if (! name) {
  1288. return Object.keys(this.fields).every(function (field) { return this$1.fields[field].passed; });
  1289. }
  1290. return this._getFieldFlag(name, 'passed');
  1291. };
  1292. FieldBag.prototype.failed = function failed (name) {
  1293. var this$1 = this;
  1294. if (! name) {
  1295. return Object.keys(this.fields).some(function (field) { return this$1.fields[field].failed; });
  1296. }
  1297. return this._getFieldFlag(name, 'failed');
  1298. };
  1299. FieldBag.prototype.clean = function clean (name) {
  1300. if (! name) {
  1301. return ! this.dirty();
  1302. }
  1303. return this._getFieldFlag(name, 'clean');
  1304. };
  1305. var LOCALE = 'en';
  1306. var STRICT_MODE = true;
  1307. var DICTIONARY = new Dictionary({
  1308. en: {
  1309. messages: messages,
  1310. attributes: {}
  1311. }
  1312. });
  1313. var Validator = function Validator(validations, options) {
  1314. if ( options === void 0 ) options = { init: true };
  1315. this.strictMode = STRICT_MODE;
  1316. this.$scopes = { __global__: {} };
  1317. this.fieldBag = new FieldBag();
  1318. this._createFields(validations);
  1319. this.errorBag = new ErrorBag();
  1320. // Some fields will be later evaluated, because the vm isn't mounted yet
  1321. // so it may register it under an inaccurate scope.
  1322. this.$deferred = [];
  1323. this.$ready = false;
  1324. // if momentjs is present, install the validators.
  1325. if (typeof moment === 'function') {
  1326. // eslint-disable-next-line
  1327. this.installDateTimeValidators(moment);
  1328. }
  1329. if (options.init) {
  1330. this.init();
  1331. }
  1332. };
  1333. var prototypeAccessors = { dictionary: {} };
  1334. /**
  1335. * @return Dictionary
  1336. */
  1337. prototypeAccessors.dictionary.get = function () {
  1338. return DICTIONARY;
  1339. };
  1340. /**
  1341. * Merges a validator object into the Rules and Messages.
  1342. *
  1343. * @param{string} name The name of the validator.
  1344. * @param{function|object} validator The validator object.
  1345. */
  1346. Validator._merge = function _merge (name, validator) {
  1347. if (isCallable(validator)) {
  1348. Rules[name] = validator;
  1349. return;
  1350. }
  1351. Rules[name] = validator.validate;
  1352. if (validator.getMessage && isCallable(validator.getMessage)) {
  1353. DICTIONARY.setMessage('en', name, validator.getMessage);
  1354. }
  1355. if (validator.messages) {
  1356. DICTIONARY.merge(
  1357. Object.keys(validator.messages).reduce(function (prev, curr) {
  1358. var dict = prev;
  1359. dict[curr] = {
  1360. messages: ( obj = {}, obj[name] = validator.messages[curr], obj )
  1361. };
  1362. var obj;
  1363. return dict;
  1364. }, {})
  1365. );
  1366. }
  1367. };
  1368. /**
  1369. * Guards from extnsion violations.
  1370. *
  1371. * @param{string} name name of the validation rule.
  1372. * @param{object} validator a validation rule object.
  1373. */
  1374. Validator._guardExtend = function _guardExtend (name, validator) {
  1375. if (Rules[name]) {
  1376. throw new ValidatorException(
  1377. ("Extension Error: There is an existing validator with the same name '" + name + "'.")
  1378. );
  1379. }
  1380. if (isCallable(validator)) {
  1381. return;
  1382. }
  1383. if (! isCallable(validator.validate)) {
  1384. throw new ValidatorException(
  1385. // eslint-disable-next-line
  1386. ("Extension Error: The validator '" + name + "' must be a function or have a 'validate' method.")
  1387. );
  1388. }
  1389. if (! isCallable(validator.getMessage) && ! isObject(validator.messages)) {
  1390. throw new ValidatorException(
  1391. // eslint-disable-next-line
  1392. ("Extension Error: The validator '" + name + "' must have a 'getMessage' method or have a 'messages' object.")
  1393. );
  1394. }
  1395. };
  1396. /**
  1397. * Static constructor.
  1398. *
  1399. * @param{object} validations The validations object.
  1400. * @return {Validator} validator A validator object.
  1401. */
  1402. Validator.create = function create (validations, $vm, options) {
  1403. return new Validator(validations, $vm, options);
  1404. };
  1405. /**
  1406. * Adds a custom validator to the list of validation rules.
  1407. *
  1408. * @param{string} name The name of the validator.
  1409. * @param{object|function} validator The validator object/function.
  1410. */
  1411. Validator.extend = function extend (name, validator) {
  1412. Validator._guardExtend(name, validator);
  1413. Validator._merge(name, validator);
  1414. };
  1415. /**
  1416. * Installs the datetime validators and the messages.
  1417. */
  1418. Validator.installDateTimeValidators = function installDateTimeValidators (moment) {
  1419. if (typeof moment !== 'function') {
  1420. warn('To use the date-time validators you must provide moment reference.');
  1421. return false;
  1422. }
  1423. if (date.installed) {
  1424. return true;
  1425. }
  1426. var validators = date.make(moment);
  1427. Object.keys(validators).forEach(function (name) {
  1428. Validator.extend(name, validators[name]);
  1429. });
  1430. Validator.updateDictionary({
  1431. en: {
  1432. messages: date.messages
  1433. }
  1434. });
  1435. date.installed = true;
  1436. return true;
  1437. };
  1438. /**
  1439. * Removes a rule from the list of validators.
  1440. * @param {String} name The name of the validator/rule.
  1441. */
  1442. Validator.remove = function remove (name) {
  1443. delete Rules[name];
  1444. };
  1445. /**
  1446. * Sets the default locale for all validators.
  1447. *
  1448. * @param {String} language The locale id.
  1449. */
  1450. Validator.setLocale = function setLocale (language) {
  1451. if ( language === void 0 ) language = 'en';
  1452. /* istanbul ignore if */
  1453. if (! DICTIONARY.hasLocale(language)) {
  1454. // eslint-disable-next-line
  1455. warn('You are setting the validator locale to a locale that is not defined in the dicitionary. English messages may still be generated.');
  1456. }
  1457. LOCALE = language;
  1458. };
  1459. /**
  1460. * Sets the operating mode for all newly created validators.
  1461. * strictMode = true: Values without a rule are invalid and cause failure.
  1462. * strictMode = false: Values without a rule are valid and are skipped.
  1463. * @param {Boolean} strictMode.
  1464. */
  1465. Validator.setStrictMode = function setStrictMode (strictMode) {
  1466. if ( strictMode === void 0 ) strictMode = true;
  1467. STRICT_MODE = strictMode;
  1468. };
  1469. /**
  1470. * Updates the dicitionary, overwriting existing values and adding new ones.
  1471. *
  1472. * @param{object} data The dictionary object.
  1473. */
  1474. Validator.updateDictionary = function updateDictionary (data) {
  1475. DICTIONARY.merge(data);
  1476. };
  1477. Validator.addLocale = function addLocale (locale) {
  1478. if (! locale.name) {
  1479. warn('Your locale must have a name property');
  1480. return;
  1481. }
  1482. this.updateDictionary(( obj = {}, obj[locale.name] = locale, obj ));
  1483. var obj;
  1484. };
  1485. Validator.prototype.addLocale = function addLocale (locale) {
  1486. Validator.addLocale(locale);
  1487. };
  1488. /**
  1489. * Resolves the scope value. Only strings and functions are allowed.
  1490. * @param {Function|String} scope
  1491. * @returns {String}
  1492. */
  1493. Validator.prototype._resolveScope = function _resolveScope (scope) {
  1494. if (typeof scope === 'string') {
  1495. return scope;
  1496. }
  1497. // The resolved value should be string.
  1498. if (isCallable(scope)) {
  1499. var value = scope();
  1500. return typeof value === 'string' ? value : '__global__';
  1501. }
  1502. return '__global__';
  1503. };
  1504. /**
  1505. * Resolves the field values from the getter functions.
  1506. */
  1507. Validator.prototype._resolveValuesFromGetters = function _resolveValuesFromGetters (scope) {
  1508. var this$1 = this;
  1509. if ( scope === void 0 ) scope = '__global__';
  1510. if (! this.$scopes[scope]) {
  1511. return {};
  1512. }
  1513. var values = {};
  1514. Object.keys(this.$scopes[scope]).forEach(function (name) {
  1515. var field = this$1.$scopes[scope][name];
  1516. var getter = field.getter;
  1517. var context = field.context;
  1518. var fieldScope = this$1._resolveScope(field.scope);
  1519. if (getter && context && (scope === '__global__' || fieldScope === scope)) {
  1520. values[name] = {
  1521. value: getter(context()),
  1522. scope: fieldScope
  1523. };
  1524. }
  1525. });
  1526. return values;
  1527. };
  1528. /**
  1529. * Creates the fields to be validated.
  1530. *
  1531. * @param{object} validations
  1532. * @return {object} Normalized object.
  1533. */
  1534. Validator.prototype._createFields = function _createFields (validations) {
  1535. var this$1 = this;
  1536. if (! validations) {
  1537. return;
  1538. }
  1539. Object.keys(validations).forEach(function (field) {
  1540. this$1._createField(field, validations[field]);
  1541. });
  1542. };
  1543. /**
  1544. * Creates a field entry in the fields object.
  1545. * @param {String} name.
  1546. * @param {String|Array} checks.
  1547. */
  1548. Validator.prototype._createField = function _createField (name, checks, scope) {
  1549. if ( scope === void 0 ) scope = '__global__';
  1550. scope = this._resolveScope(scope);
  1551. if (! this.$scopes[scope]) {
  1552. this.$scopes[scope] = {};
  1553. }
  1554. if (! this.$scopes[scope][name]) {
  1555. this.$scopes[scope][name] = {};
  1556. }
  1557. var field = this.$scopes[scope][name];
  1558. this.fieldBag._addIfNotExists(name);
  1559. field.validations = this._normalizeRules(name, checks, scope);
  1560. field.required = this._isRequired(field);
  1561. };
  1562. /**
  1563. * Normalizes rules.
  1564. * @return {Object}
  1565. */
  1566. Validator.prototype._normalizeRules = function _normalizeRules (name, checks, scope) {
  1567. if (! checks) { return {}; }
  1568. if (typeof checks === 'string') {
  1569. return this._normalizeString(checks);
  1570. }
  1571. if (! isObject(checks)) {
  1572. warn(("Your checks for '" + scope + "." + name + "' must be either a string or an object."));
  1573. return {};
  1574. }
  1575. return this._normalizeObject(checks);
  1576. };
  1577. /**
  1578. * Checks if a field has a required rule.
  1579. */
  1580. Validator.prototype._isRequired = function _isRequired (field) {
  1581. return field.validations && field.validations.required;
  1582. };
  1583. /**
  1584. * Normalizes an object of rules.
  1585. */
  1586. Validator.prototype._normalizeObject = function _normalizeObject (rules) {
  1587. var this$1 = this;
  1588. var validations = {};
  1589. Object.keys(rules).forEach(function (rule) {
  1590. var params = [];
  1591. if (rules[rule] === true) {
  1592. params = [];
  1593. } else if (Array.isArray(rules[rule])) {
  1594. params = rules[rule];
  1595. } else {
  1596. params = [rules[rule]];
  1597. }
  1598. if (rules[rule] === false) {
  1599. delete validations[rule];
  1600. } else {
  1601. validations[rule] = params;
  1602. }
  1603. if (date.installed && this$1._isADateRule(rule)) {
  1604. validations[rule].push(this$1._getDateFormat(validations));
  1605. }
  1606. });
  1607. return validations;
  1608. };
  1609. /**
  1610. * Date rules need the existance of a format, so date_format must be supplied.
  1611. * @param {String} name The rule name.
  1612. * @param {Array} validations the field validations.
  1613. */
  1614. Validator.prototype._getDateFormat = function _getDateFormat (validations) {
  1615. if (validations.date_format && Array.isArray(validations.date_format)) {
  1616. return validations.date_format[0];
  1617. }
  1618. return null;
  1619. };
  1620. /**
  1621. * Checks if the passed rule is a date rule.
  1622. */
  1623. Validator.prototype._isADateRule = function _isADateRule (rule) {
  1624. return !! ~['after', 'before', 'date_between'].indexOf(rule);
  1625. };
  1626. /**
  1627. * Normalizes string rules.
  1628. * @param {String} rules The rules that will be normalized.
  1629. * @param {Object} field The field object that is being operated on.
  1630. */
  1631. Validator.prototype._normalizeString = function _normalizeString (rules) {
  1632. var this$1 = this;
  1633. var validations = {};
  1634. rules.split('|').forEach(function (rule) {
  1635. var parsedRule = this$1._parseRule(rule);
  1636. if (! parsedRule.name) {
  1637. return;
  1638. }
  1639. if (parsedRule.name === 'required') {
  1640. validations.required = true;
  1641. }
  1642. validations[parsedRule.name] = parsedRule.params;
  1643. if (date.installed && this$1._isADateRule(parsedRule.name)) {
  1644. validations[parsedRule.name].push(this$1._getDateFormat(validations));
  1645. }
  1646. });
  1647. return validations;
  1648. };
  1649. /**
  1650. * Normalizes a string rule.
  1651. *
  1652. * @param {string} rule The rule to be normalized.
  1653. * @return {object} rule The normalized rule.
  1654. */
  1655. Validator.prototype._parseRule = function _parseRule (rule) {
  1656. var params = [];
  1657. var name = rule.split(':')[0];
  1658. if (~rule.indexOf(':')) {
  1659. params = rule.split(':').slice(1).join(':').split(',');
  1660. }
  1661. return { name: name, params: params };
  1662. };
  1663. /**
  1664. * Formats an error message for field and a rule.
  1665. *
  1666. * @param{string} field The field name.
  1667. * @param{object} rule Normalized rule object.
  1668. * @param {object} data Additional Information about the validation result.
  1669. * @param {string} scope The field scope.
  1670. * @return {string} Formatted error message.
  1671. */
  1672. Validator.prototype._formatErrorMessage = function _formatErrorMessage (field, rule, data, scope) {
  1673. if ( data === void 0 ) data = {};
  1674. if ( scope === void 0 ) scope = '__global__';
  1675. var name = this._getFieldDisplayName(field, scope);
  1676. var params = this._getLocalizedParams(rule, scope);
  1677. // Defaults to english message.
  1678. if (! this.dictionary.hasLocale(LOCALE)) {
  1679. return this.dictionary.getMessage('en', rule.name)(name, params, data);
  1680. }
  1681. return this.dictionary.getMessage(LOCALE, rule.name)(name, params, data);
  1682. };
  1683. /**
  1684. * Translates the parameters passed to the rule (mainly for target fields).
  1685. */
  1686. Validator.prototype._getLocalizedParams = function _getLocalizedParams (rule, scope) {
  1687. if ( scope === void 0 ) scope = '__global__';
  1688. if (~ ['after', 'before', 'confirmed'].indexOf(rule.name) &&
  1689. rule.params && rule.params[0]) {
  1690. var param = this.$scopes[scope][rule.params[0]];
  1691. if (param && param.name) { return [param.name]; }
  1692. return [this.dictionary.getAttribute(LOCALE, rule.params[0], rule.params[0])];
  1693. }
  1694. return rule.params;
  1695. };
  1696. /**
  1697. * Resolves an appropiate display name, first checking 'data-as' or the registered 'prettyName'
  1698. * Then the dictionary, then fallsback to field name.
  1699. * @return {String} displayName The name to be used in the errors.
  1700. */
  1701. Validator.prototype._getFieldDisplayName = function _getFieldDisplayName (field, scope) {
  1702. if ( scope === void 0 ) scope = '__global__';
  1703. return this.$scopes[scope][field].name || this.dictionary.getAttribute(LOCALE, field, field);
  1704. };
  1705. /**
  1706. * Tests a single input value against a rule.
  1707. *
  1708. * @param{*} name The name of the field.
  1709. * @param{*} valuethe value of the field.
  1710. * @param{object} rule the rule object.
  1711. * @param {scope} scope The field scope.
  1712. * @return {boolean} Whether it passes the check.
  1713. */
  1714. Validator.prototype._test = function _test (name, value, rule, scope) {
  1715. var this$1 = this;
  1716. if ( scope === void 0 ) scope = '__global__';
  1717. var validator = Rules[rule.name];
  1718. if (! validator || typeof validator !== 'function') {
  1719. throw new ValidatorException(("No such validator '" + (rule.name) + "' exists."));
  1720. }
  1721. var result = validator(value, rule.params, name);
  1722. // If it is a promise.
  1723. if (isCallable(result.then)) {
  1724. return result.then(function (values) {
  1725. var allValid = true;
  1726. var data = {};
  1727. if (Array.isArray(values)) {
  1728. allValid = values.every(function (t) { return t.valid; });
  1729. } else { // Is a single object.
  1730. allValid = values.valid;
  1731. data = values.data;
  1732. }
  1733. if (! allValid) {
  1734. this$1.errorBag.add(
  1735. name,
  1736. this$1._formatErrorMessage(name, rule, data, scope),
  1737. rule.name,
  1738. scope
  1739. );
  1740. }
  1741. return allValid;
  1742. });
  1743. }
  1744. if (! isObject(result)) {
  1745. result = { valid: result, data: {} };
  1746. }
  1747. if (! result.valid) {
  1748. this.errorBag.add(
  1749. name,
  1750. this._formatErrorMessage(name, rule, result.data, scope),
  1751. rule.name,
  1752. scope
  1753. );
  1754. }
  1755. return result.valid;
  1756. };
  1757. /**
  1758. * Registers a field to be validated.
  1759. *
  1760. * @param{string} name The field name.
  1761. * @param{String|Array|Object} checks validations expression.
  1762. * @param {string} prettyName Custom name to be used as field name in error messages.
  1763. * @param {Function} getter A function used to retrive a fresh value for the field.
  1764. */
  1765. Validator.prototype.attach = function attach (name, checks, options) {
  1766. var this$1 = this;
  1767. if ( options === void 0 ) options = {};
  1768. var attach = function () {
  1769. options.scope = this$1._resolveScope(options.scope);
  1770. this$1.updateField(name, checks, options);
  1771. var field = this$1.$scopes[options.scope][name];
  1772. field.scope = options.scope;
  1773. field.name = options.prettyName;
  1774. field.getter = options.getter;
  1775. field.context = options.context;
  1776. field.listeners = options.listeners || { detach: function detach() {} };
  1777. field.el = field.listeners.el;
  1778. this$1._setAriaRequiredAttribute(field);
  1779. this$1._setAriaValidAttribute(field, true);
  1780. };
  1781. var scope = isCallable(options.scope) ? options.scope() : options.scope;
  1782. if (! scope && ! this.$ready) {
  1783. this.$deferred.push(attach);
  1784. return;
  1785. }
  1786. attach();
  1787. };
  1788. /**
  1789. * Initializes the non-scoped fields and any bootstrap logic.
  1790. */
  1791. Validator.prototype.init = function init () {
  1792. this.$ready = true;
  1793. this.$deferred.forEach(function (attach) {
  1794. attach();
  1795. });
  1796. this.$deferred = [];
  1797. return this;
  1798. };
  1799. /**
  1800. * Append another validation to an existing field.
  1801. *
  1802. * @param{string} name The field name.
  1803. * @param{string} checks validations expression.
  1804. */
  1805. Validator.prototype.append = function append (name, checks, options) {
  1806. if ( options === void 0 ) options = {};
  1807. options.scope = this._resolveScope(options.scope);
  1808. // No such field
  1809. if (! this.$scopes[options.scope] || ! this.$scopes[options.scope][name]) {
  1810. this.attach(name, checks, options);
  1811. }
  1812. var field = this.$scopes[options.scope][name];
  1813. var newChecks = this._normalizeRules(name, checks, options.scope);
  1814. Object.keys(newChecks).forEach(function (key) {
  1815. field.validations[key] = newChecks[key];
  1816. });
  1817. };
  1818. /**
  1819. * Updates the field rules with new ones.
  1820. */
  1821. Validator.prototype.updateField = function updateField (name, checks, options) {
  1822. if ( options === void 0 ) options = {};
  1823. var field = (this.$scopes[options.scope] && this.$scopes[options.scope][name]) || null;
  1824. var oldChecks = field ? JSON.stringify(field.validations) : '';
  1825. this._createField(name, checks, options.scope);
  1826. field = (this.$scopes[options.scope] && this.$scopes[options.scope][name]) || null;
  1827. var newChecks = field ? JSON.stringify(field.validations) : '';
  1828. // compare both newChecks and oldChecks to make sure we don't trigger uneccessary directive
  1829. // update by changing the errorBag (prevents infinite loops).
  1830. if (newChecks !== oldChecks) {
  1831. this.errorBag.remove(name, options.scope);
  1832. }
  1833. };
  1834. /**
  1835. * Removes a field from the validator.
  1836. *
  1837. * @param{String} name The name of the field.
  1838. * @param {String} scope The name of the field scope.
  1839. */
  1840. Validator.prototype.detach = function detach (name, scope) {
  1841. if ( scope === void 0 ) scope = '__global__';
  1842. // No such field.
  1843. if (! this.$scopes[scope] || ! this.$scopes[scope][name]) {
  1844. return;
  1845. }
  1846. this.$scopes[scope][name].listeners.detach();
  1847. this.errorBag.remove(name, scope);
  1848. this.fieldBag._remove(name);
  1849. delete this.$scopes[scope][name];
  1850. };
  1851. /**
  1852. * Adds a custom validator to the list of validation rules.
  1853. *
  1854. * @param{string} name The name of the validator.
  1855. * @param{object|function} validator The validator object/function.
  1856. */
  1857. Validator.prototype.extend = function extend (name, validator) {
  1858. Validator.extend(name, validator);
  1859. };
  1860. /**
  1861. * Gets the internal errorBag instance.
  1862. *
  1863. * @return {ErrorBag} errorBag The internal error bag object.
  1864. */
  1865. Validator.prototype.getErrors = function getErrors () {
  1866. return this.errorBag;
  1867. };
  1868. /**
  1869. * Gets the currently active locale.
  1870. *
  1871. * @return {String} Locale identifier.
  1872. */
  1873. Validator.prototype.getLocale = function getLocale () {
  1874. return LOCALE;
  1875. };
  1876. /**
  1877. * Just an alias to the static method for convienece.
  1878. */
  1879. Validator.prototype.installDateTimeValidators = function installDateTimeValidators (moment) {
  1880. Validator.installDateTimeValidators(moment);
  1881. };
  1882. /**
  1883. * Removes a rule from the list of validators.
  1884. * @param {String} name The name of the validator/rule.
  1885. */
  1886. Validator.prototype.remove = function remove (name) {
  1887. Validator.remove(name);
  1888. };
  1889. /**
  1890. * Sets the validator current langauge.
  1891. *
  1892. * @param {string} language locale or language id.
  1893. */
  1894. Validator.prototype.setLocale = function setLocale (language) {
  1895. /* istanbul ignore if */
  1896. if (! this.dictionary.hasLocale(language)) {
  1897. // eslint-disable-next-line
  1898. warn('You are setting the validator locale to a locale that is not defined in the dicitionary. English messages may still be generated.');
  1899. }
  1900. LOCALE = language;
  1901. };
  1902. /**
  1903. * Sets the operating mode for this validator.
  1904. * strictMode = true: Values without a rule are invalid and cause failure.
  1905. * strictMode = false: Values without a rule are valid and are skipped.
  1906. * @param {Boolean} strictMode.
  1907. */
  1908. Validator.prototype.setStrictMode = function setStrictMode (strictMode) {
  1909. if ( strictMode === void 0 ) strictMode = true;
  1910. this.strictMode = strictMode;
  1911. };
  1912. /**
  1913. * Updates the messages dicitionary, overwriting existing values and adding new ones.
  1914. *
  1915. * @param{object} data The messages object.
  1916. */
  1917. Validator.prototype.updateDictionary = function updateDictionary (data) {
  1918. Validator.updateDictionary(data);
  1919. };
  1920. /**
  1921. * Adds a scope.
  1922. */
  1923. Validator.prototype.addScope = function addScope (scope) {
  1924. if (scope && ! this.$scopes[scope]) {
  1925. this.$scopes[scope] = {};
  1926. }
  1927. };
  1928. /**
  1929. * Validates a value against a registered field validations.
  1930. *
  1931. * @param{string} name the field name.
  1932. * @param{*} value The value to be validated.
  1933. * @param {String} scope The scope of the field.
  1934. * @return {Promise}
  1935. */
  1936. Validator.prototype.validate = function validate (name, value, scope) {
  1937. var this$1 = this;
  1938. if ( scope === void 0 ) scope = '__global__';
  1939. if (name && name.indexOf('.') > -1) {
  1940. // no such field, try the scope form.
  1941. if (! this.$scopes.__global__[name]) {
  1942. var assign$$1;
  1943. (assign$$1 = name.split('.'), scope = assign$$1[0], name = assign$$1[1]);
  1944. }
  1945. }
  1946. if (! scope) { scope = '__global__'; }
  1947. if (! this.$scopes[scope] || ! this.$scopes[scope][name]) {
  1948. if (! this.strictMode) { return Promise.resolve(true); }
  1949. var fullName = scope === '__global__' ? name : (scope + "." + name);
  1950. warn(("Validating a non-existant field: \"" + fullName + "\". Use \"attach()\" first."));
  1951. return Promise.reject(false);
  1952. }
  1953. var field = this.$scopes[scope][name];
  1954. this.errorBag.remove(name, scope);
  1955. // if its not required and is empty or null or undefined then it passes.
  1956. if (! field.required && ~[null, undefined, ''].indexOf(value)) {
  1957. this.fieldBag._setFlags(name, { valid: true, dirty: true });
  1958. return Promise.resolve(true);
  1959. }
  1960. var promises = [];
  1961. var test = Object.keys(field.validations).every(function (rule) {
  1962. var result = this$1._test(
  1963. name,
  1964. value,
  1965. { name: rule, params: field.validations[rule] },
  1966. scope
  1967. );
  1968. if (isCallable(result.then)) {
  1969. promises.push(result);
  1970. }
  1971. return result;
  1972. });
  1973. if (promises.length) {
  1974. return Promise.all(promises).then(function (values) {
  1975. var valid = values.every(function (t) { return t; }) && test;
  1976. this$1.fieldBag._setFlags(name, { valid: valid, dirty: true });
  1977. this$1._setAriaValidAttribute(field, test);
  1978. return valid;
  1979. });
  1980. }
  1981. this.fieldBag._setFlags(name, { valid: test, dirty: true });
  1982. this._setAriaValidAttribute(field, test);
  1983. return new Promise(function (resolve, reject) {
  1984. if (test) {
  1985. resolve(test);
  1986. return;
  1987. }
  1988. reject(false);
  1989. });
  1990. };
  1991. /**
  1992. * Sets the aria-invalid attribute on the element.
  1993. */
  1994. Validator.prototype._setAriaValidAttribute = function _setAriaValidAttribute (field, valid) {
  1995. if (! field.el) {
  1996. return;
  1997. }
  1998. field.el.setAttribute('aria-invalid', !valid);
  1999. };
  2000. /**
  2001. * Sets the aria-required attribute on the element.
  2002. */
  2003. Validator.prototype._setAriaRequiredAttribute = function _setAriaRequiredAttribute (field) {
  2004. if (! field.el) {
  2005. return;
  2006. }
  2007. field.el.setAttribute('aria-required', !! field.required);
  2008. };
  2009. /**
  2010. * Validates each value against the corresponding field validations.
  2011. * @param{object} values The values to be validated.
  2012. * @return {Promise} Returns a promise with the validation result.
  2013. */
  2014. Validator.prototype.validateAll = function validateAll (values) {
  2015. var this$1 = this;
  2016. var normalizedValues;
  2017. if (! values || typeof values === 'string') {
  2018. this.errorBag.clear(values);
  2019. normalizedValues = this._resolveValuesFromGetters(values);
  2020. } else {
  2021. normalizedValues = {};
  2022. Object.keys(values).forEach(function (key) {
  2023. normalizedValues[key] = {
  2024. value: values[key]
  2025. };
  2026. });
  2027. }
  2028. var promises = Object.keys(normalizedValues).map(function (property) { return this$1.validate(
  2029. property,
  2030. normalizedValues[property].value,
  2031. normalizedValues[property].scope
  2032. ); });
  2033. return Promise.all(promises).then(function () { return true; }).catch(function () {
  2034. throw new ValidatorException('Validation Failed');
  2035. });
  2036. };
  2037. /**
  2038. * Validates all scopes.
  2039. * @returns {Promise} All promises resulted from each scope.
  2040. */
  2041. Validator.prototype.validateScopes = function validateScopes () {
  2042. var this$1 = this;
  2043. return Promise.all(
  2044. Object.keys(this.$scopes).map(function (scope) { return this$1.validateAll(scope); })
  2045. );
  2046. };
  2047. Object.defineProperties( Validator.prototype, prototypeAccessors );
  2048. var makeMixin = function (Vue, options) { return ({
  2049. computed: ( obj = {}, obj[options.errorBagName] = {
  2050. get: function get() {
  2051. return this.$validator.errorBag;
  2052. }
  2053. }, obj[options.fieldsBagName] = {
  2054. get: function get() {
  2055. return this.$validator.fieldBag;
  2056. }
  2057. }, obj ),
  2058. beforeCreate: function beforeCreate() {
  2059. this.$validator = new Validator(null, { init: false });
  2060. Vue.util.defineReactive(this.$validator, 'errorBag', this.$validator.errorBag);
  2061. Vue.util.defineReactive(this.$validator, 'fieldBag', this.$validator.fieldBag);
  2062. },
  2063. mounted: function mounted() {
  2064. this.$validator.init();
  2065. }
  2066. })
  2067. var obj; };
  2068. var ListenerGenerator = function ListenerGenerator(el, binding, vnode, options) {
  2069. this.unwatch = undefined;
  2070. this.callbacks = [];
  2071. this.el = el;
  2072. this.scope = isObject(binding.value) ? binding.value.scope : getScope(el);
  2073. this.binding = binding;
  2074. this.vm = vnode.context;
  2075. this.component = vnode.child;
  2076. this.options = options;
  2077. this.fieldName = this._resolveFieldName();
  2078. this.model = this._resolveModel(vnode.data.directives);
  2079. };
  2080. /**
  2081. * Checks if the node directives contains a v-model.
  2082. */
  2083. ListenerGenerator.prototype._resolveModel = function _resolveModel (directives) {
  2084. var expRegex = /^[a-z_]+[0-9]*(\w*\.[a-z_]\w*)*$/i;
  2085. var model = find(directives, function (d) { return d.name === 'model' && expRegex.test(d.expression); });
  2086. return model && this._isExistingPath(model.expression) && model.expression;
  2087. };
  2088. /**
  2089. * Checks if the object path exists.
  2090. */
  2091. ListenerGenerator.prototype._isExistingPath = function _isExistingPath (path) {
  2092. var obj = this.vm;
  2093. return path.split('.').every(function (prop) {
  2094. if (! Object.prototype.hasOwnProperty.call(obj, prop)) {
  2095. return false;
  2096. }
  2097. obj = obj[prop];
  2098. return true;
  2099. });
  2100. };
  2101. /**
  2102. * Resolves the field name to trigger validations.
  2103. * @return {String} The field name.
  2104. */
  2105. ListenerGenerator.prototype._resolveFieldName = function _resolveFieldName () {
  2106. if (this.component) {
  2107. return getDataAttribute(this.el, 'name') || this.component.name;
  2108. }
  2109. return getDataAttribute(this.el, 'name') || this.el.name;
  2110. };
  2111. /**
  2112. * Determines if the validation rule requires additional listeners on target fields.
  2113. */
  2114. ListenerGenerator.prototype._hasFieldDependency = function _hasFieldDependency (rules) {
  2115. var this$1 = this;
  2116. var fieldName = false;
  2117. if (! rules) {
  2118. return false;
  2119. }
  2120. if (isObject(rules)) {
  2121. Object.keys(rules).forEach(function (r) { // eslint-disable-line
  2122. if (/confirmed|after|before/.test(r)) {
  2123. fieldName = rules[r];
  2124. return false;
  2125. }
  2126. });
  2127. return fieldName;
  2128. }
  2129. rules.split('|').every(function (r) {
  2130. if (/\b(confirmed|after|before):/.test(r)) {
  2131. fieldName = r.split(':')[1];
  2132. return false;
  2133. }
  2134. if (/\b(confirmed)/.test(r)) {
  2135. fieldName = (this$1.fieldName) + "_confirmation";
  2136. return false;
  2137. }
  2138. return true;
  2139. });
  2140. return fieldName;
  2141. };
  2142. /**
  2143. * Validates input value, triggered by 'input' event.
  2144. */
  2145. ListenerGenerator.prototype._inputListener = function _inputListener () {
  2146. this._validate(this.el.value);
  2147. };
  2148. /**
  2149. * Validates files, triggered by 'change' event.
  2150. */
  2151. ListenerGenerator.prototype._fileListener = function _fileListener () {
  2152. var isValid = this._validate(toArray(this.el.files));
  2153. if (! isValid && this.binding.modifiers.reject) {
  2154. this.el.value = '';
  2155. }
  2156. };
  2157. /**
  2158. * Validates radio buttons, triggered by 'change' event.
  2159. */
  2160. ListenerGenerator.prototype._radioListener = function _radioListener () {
  2161. var checked = document.querySelector(("input[name=\"" + (this.el.name) + "\"]:checked"));
  2162. this._validate(checked ? checked.value : null);
  2163. };
  2164. /**
  2165. * Validates checkboxes, triggered by change event.
  2166. */
  2167. ListenerGenerator.prototype._checkboxListener = function _checkboxListener () {
  2168. var this$1 = this;
  2169. var checkedBoxes = document.querySelectorAll(("input[name=\"" + (this.el.name) + "\"]:checked"));
  2170. if (! checkedBoxes || ! checkedBoxes.length) {
  2171. this._validate(null);
  2172. return;
  2173. }
  2174. toArray(checkedBoxes).forEach(function (box) {
  2175. this$1._validate(box.value);
  2176. });
  2177. };
  2178. /**
  2179. * Trigger the validation for a specific value.
  2180. */
  2181. ListenerGenerator.prototype._validate = function _validate (value) {
  2182. return this.vm.$validator.validate(
  2183. this.fieldName, value, this.scope || getScope(this.el)
  2184. ).catch(function (result) {
  2185. return result;
  2186. });
  2187. };
  2188. /**
  2189. * Returns a scoped callback, only runs if the el scope is the same as the recieved scope
  2190. * From the event.
  2191. */
  2192. ListenerGenerator.prototype._getScopedListener = function _getScopedListener (callback) {
  2193. var this$1 = this;
  2194. return function (scope) {
  2195. if (! scope || scope === this$1.scope || scope instanceof window.Event) {
  2196. callback();
  2197. }
  2198. };
  2199. };
  2200. /**
  2201. * Attaches validator event-triggered validation.
  2202. */
  2203. ListenerGenerator.prototype._attachValidatorEvent = function _attachValidatorEvent () {
  2204. var this$1 = this;
  2205. var listener = this._getScopedListener(this._getSuitableListener().listener.bind(this));
  2206. var fieldName = this._hasFieldDependency(
  2207. getRules(this.binding.expression, this.binding.value, this.el)
  2208. );
  2209. if (fieldName) {
  2210. // Wait for the validator ready triggered when vm is mounted because maybe
  2211. // the element isn't mounted yet.
  2212. this.vm.$nextTick(function () {
  2213. var target = document.querySelector(("input[name='" + fieldName + "']"));
  2214. if (! target) {
  2215. warn('Cannot find target field, no additional listeners were attached.');
  2216. return;
  2217. }
  2218. target.addEventListener('input', listener);
  2219. this$1.callbacks.push({ name: 'input', listener: listener, el: target });
  2220. });
  2221. }
  2222. };
  2223. /**
  2224. * Determines a suitable listener for the element.
  2225. */
  2226. ListenerGenerator.prototype._getSuitableListener = function _getSuitableListener () {
  2227. var listener;
  2228. if (this.el.tagName === 'SELECT') {
  2229. return {
  2230. names: ['change', 'blur'],
  2231. listener: this._inputListener
  2232. };
  2233. }
  2234. // determine the suitable listener and events to handle
  2235. switch (this.el.type) {
  2236. case 'file':
  2237. listener = {
  2238. names: ['change'],
  2239. listener: this._fileListener
  2240. };
  2241. break;
  2242. case 'radio':
  2243. listener = {
  2244. names: ['change'],
  2245. listener: this._radioListener
  2246. };
  2247. break;
  2248. case 'checkbox':
  2249. listener = {
  2250. names: ['change'],
  2251. listener: this._checkboxListener
  2252. };
  2253. break;
  2254. default:
  2255. listener = {
  2256. names: ['input', 'blur'],
  2257. listener: this._inputListener
  2258. };
  2259. break;
  2260. }
  2261. // users are able to specify which events they want to validate on
  2262. // pipe separated list of handler names to use
  2263. var events = getDataAttribute(this.el, 'validate-on');
  2264. if (events) {
  2265. listener.names = events.split('|');
  2266. }
  2267. return listener;
  2268. };
  2269. /**
  2270. * Attaches neccessary validation events for the component.
  2271. */
  2272. ListenerGenerator.prototype._attachComponentListeners = function _attachComponentListeners () {
  2273. var this$1 = this;
  2274. this.componentListener = debounce(function (value) {
  2275. this$1._validate(value);
  2276. }, getDataAttribute(this.el, 'delay') || this.options.delay);
  2277. this.component.$on('input', this.componentListener);
  2278. };
  2279. /**
  2280. * Attachs a suitable listener for the input.
  2281. */
  2282. ListenerGenerator.prototype._attachFieldListeners = function _attachFieldListeners () {
  2283. var this$1 = this;
  2284. // If it is a component, use vue events instead.
  2285. if (this.component) {
  2286. this._attachComponentListeners();
  2287. return;
  2288. }
  2289. var handler = this._getSuitableListener();
  2290. var listener = debounce(
  2291. handler.listener.bind(this),
  2292. getDataAttribute(this.el, 'delay') || this.options.delay
  2293. );
  2294. if (~['radio', 'checkbox'].indexOf(this.el.type)) {
  2295. this.vm.$nextTick(function () {
  2296. var elms = document.querySelectorAll(("input[name=\"" + (this$1.el.name) + "\"]"));
  2297. toArray(elms).forEach(function (input) {
  2298. handler.names.forEach(function (handlerName) {
  2299. input.addEventListener(handlerName, listener);
  2300. this$1.callbacks.push({ name: handlerName, listener: listener, el: input });
  2301. });
  2302. });
  2303. });
  2304. return;
  2305. }
  2306. handler.names.forEach(function (handlerName) {
  2307. this$1.el.addEventListener(handlerName, listener);
  2308. this$1.callbacks.push({ name: handlerName, listener: listener, el: this$1.el });
  2309. });
  2310. };
  2311. /**
  2312. * Returns a context, getter factory pairs for each input type.
  2313. */
  2314. ListenerGenerator.prototype._resolveValueGetter = function _resolveValueGetter () {
  2315. var this$1 = this;
  2316. if (this.component) {
  2317. return {
  2318. context: function () { return this$1.component; },
  2319. getter: function getter(context) {
  2320. return context[getDataAttribute(context.$el, 'value-path')] || context.value;
  2321. }
  2322. };
  2323. }
  2324. switch (this.el.type) {
  2325. case 'checkbox': return {
  2326. context: function () { return document.querySelectorAll(("input[name=\"" + (this$1.el.name) + "\"]:checked")); },
  2327. getter: function getter(context) {
  2328. if (! context || ! context.length) {
  2329. return null;
  2330. }
  2331. return toArray(context).map(function (checkbox) { return checkbox.value; });
  2332. }
  2333. };
  2334. case 'radio': return {
  2335. context: function () { return document.querySelector(("input[name=\"" + (this$1.el.name) + "\"]:checked")); },
  2336. getter: function getter(context) {
  2337. return context && context.value;
  2338. }
  2339. };
  2340. case 'file': return {
  2341. context: function () { return this$1.el; },
  2342. getter: function getter(context) {
  2343. return toArray(context.files);
  2344. }
  2345. };
  2346. default: return {
  2347. context: function () { return this$1.el; },
  2348. getter: function getter(context) {
  2349. return context.value;
  2350. }
  2351. };
  2352. }
  2353. };
  2354. /*
  2355. * Gets the arg string value, either from the directive or the expression value.
  2356. */
  2357. ListenerGenerator.prototype._getArg = function _getArg () {
  2358. // Get it from the directive arg.
  2359. if (this.binding.arg) {
  2360. return this.binding.arg;
  2361. }
  2362. // Get it from v-model.
  2363. if (this.model) {
  2364. return this.model;
  2365. }
  2366. return isObject(this.binding.value) ? this.binding.value.arg : null;
  2367. };
  2368. /**
  2369. * Attaches model watchers and extra listeners.
  2370. */
  2371. ListenerGenerator.prototype._attachModelWatcher = function _attachModelWatcher (arg) {
  2372. var this$1 = this;
  2373. var events = getDataAttribute(this.el, 'validate-on') || 'input|blur';
  2374. var listener = debounce(
  2375. this._getSuitableListener().listener.bind(this),
  2376. getDataAttribute(this.el, 'delay') || this.options.delay
  2377. );
  2378. events.split('|').forEach(function (name) {
  2379. if (~['input', 'change'].indexOf(name)) {
  2380. var debounced = debounce(function (value) {
  2381. this$1.vm.$validator.validate(
  2382. this$1.fieldName, value, this$1.scope || getScope(this$1.el)
  2383. ).catch(function (result) {
  2384. return result
  2385. });
  2386. }, getDataAttribute(this$1.el, 'delay') || this$1.options.delay);
  2387. this$1.unwatch = this$1.vm.$watch(arg, debounced, { deep: true });
  2388. // No need to attach it on element as it will use the vue watcher.
  2389. return;
  2390. }
  2391. this$1.el.addEventListener(name, listener);
  2392. this$1.callbacks.push({ name: name, listener: listener, el: this$1.el });
  2393. });
  2394. };
  2395. /**
  2396. * Attaches the Event Listeners.
  2397. */
  2398. ListenerGenerator.prototype.attach = function attach () {
  2399. var this$1 = this;
  2400. var ref = this._resolveValueGetter();
  2401. var context = ref.context;
  2402. var getter = ref.getter;
  2403. this.vm.$validator.attach(
  2404. this.fieldName,
  2405. getRules(this.binding.expression, this.binding.value, this.el), {
  2406. // eslint-disable-next-line
  2407. scope: function () {
  2408. return this$1.scope || getScope(this$1.el);
  2409. },
  2410. prettyName: getDataAttribute(this.el, 'as') || this.el.title,
  2411. context: context,
  2412. getter: getter,
  2413. listeners: this
  2414. }
  2415. );
  2416. this._attachValidatorEvent();
  2417. var arg = this._getArg();
  2418. if (arg) {
  2419. this._attachModelWatcher(arg);
  2420. return;
  2421. }
  2422. this._attachFieldListeners();
  2423. };
  2424. /**
  2425. * Removes all attached event listeners.
  2426. */
  2427. ListenerGenerator.prototype.detach = function detach () {
  2428. if (this.component) {
  2429. this.component.$off('input', this.componentListener);
  2430. }
  2431. if (this.unwatch) {
  2432. this.unwatch();
  2433. }
  2434. this.callbacks.forEach(function (h) {
  2435. h.el.removeEventListener(h.name, h.listener);
  2436. });
  2437. this.callbacks = [];
  2438. };
  2439. var listenersInstances = [];
  2440. function addClasses(el, flags, classNames) {
  2441. if (! flags) { return; }
  2442. if (flags.dirty) {
  2443. addClass(el, classNames.touched);
  2444. removeClass(el, classNames.untouched);
  2445. } else {
  2446. addClass(el, classNames.untouched);
  2447. removeClass(el, classNames.touched);
  2448. }
  2449. if (flags.valid || flags.passed) {
  2450. addClass(el, classNames.valid);
  2451. removeClass(el, classNames.invalid);
  2452. } else {
  2453. addClass(el, classNames.invalid);
  2454. removeClass(el, classNames.valid);
  2455. }
  2456. }
  2457. function setDirty(el, classNames) {
  2458. addClass(el, classNames.dirty);
  2459. removeClass(el, classNames.pristine);
  2460. }
  2461. function setPristine(el, classNames) {
  2462. addClass(el, classNames.pristine);
  2463. removeClass(el, classNames.dirty);
  2464. }
  2465. var makeDirective = function (options) { return ({
  2466. inserted: function inserted(el, binding, vnode) {
  2467. var listener = new ListenerGenerator(el, binding, vnode, options);
  2468. listener.attach();
  2469. listenersInstances.push({ vm: vnode.context, el: el, instance: listener });
  2470. if (options.enableAutoClasses) {
  2471. setPristine(el, options.classNames);
  2472. el.onfocus = function () { setDirty(el, options.classNames); };
  2473. addClasses(
  2474. el,
  2475. vnode.context.$validator.fieldBag.fields[listener.fieldName],
  2476. options.classNames
  2477. );
  2478. }
  2479. },
  2480. update: function update(el, ref, ref$1) {
  2481. var expression = ref.expression;
  2482. var value = ref.value;
  2483. var oldValue = ref.oldValue;
  2484. var context = ref$1.context;
  2485. var ref$2 = find(listenersInstances, function (l) { return l.vm === context && l.el === el; });
  2486. var instance = ref$2.instance;
  2487. if (options.enableAutoClasses) {
  2488. addClasses(el, context.$validator.fieldBag.fields[instance.fieldName], options.classNames);
  2489. }
  2490. // make sure we don't do uneccessary work if no expression was passed
  2491. // nor if the expression did not change.
  2492. if (! expression || (instance.cachedExp === JSON.stringify(value))) { return; }
  2493. instance.cachedExp = JSON.stringify(value);
  2494. var scope = isObject(value) ? (value.scope || getScope(el)) : getScope(el);
  2495. context.$validator.updateField(
  2496. instance.fieldName,
  2497. getRules(expression, value, el),
  2498. { scope: scope || '__global__' }
  2499. );
  2500. },
  2501. unbind: function unbind(el, ref, ref$1) {
  2502. var value = ref.value;
  2503. var context = ref$1.context;
  2504. var holder = find(listenersInstances, function (l) { return l.vm === context && l.el === el; });
  2505. if (typeof holder === 'undefined') {
  2506. return;
  2507. }
  2508. var scope = isObject(value) ? value.scope : (getScope(el) || '__global__');
  2509. context.$validator.detach(holder.instance.fieldName, scope);
  2510. listenersInstances.splice(listenersInstances.indexOf(holder), 1);
  2511. }
  2512. }); };
  2513. var DEFAULT_CLASS_NAMES = {
  2514. touched: 'touched', // the control has been blurred
  2515. untouched: 'untouched', // the control hasn't been blurred
  2516. valid: 'valid', // model is valid
  2517. invalid: 'invalid', // model is invalid
  2518. pristine: 'pristine', // control has not been interacted with
  2519. dirty: 'dirty' // control has been interacted with
  2520. };
  2521. // eslint-disable-next-line
  2522. var install = function (Vue, ref) {
  2523. if ( ref === void 0 ) ref = {};
  2524. var locale = ref.locale; if ( locale === void 0 ) locale = 'en';
  2525. var delay = ref.delay; if ( delay === void 0 ) delay = 0;
  2526. var errorBagName = ref.errorBagName; if ( errorBagName === void 0 ) errorBagName = 'errors';
  2527. var dictionary = ref.dictionary; if ( dictionary === void 0 ) dictionary = null;
  2528. var strict = ref.strict; if ( strict === void 0 ) strict = true;
  2529. var fieldsBagName = ref.fieldsBagName; if ( fieldsBagName === void 0 ) fieldsBagName = 'fields';
  2530. var enableAutoClasses = ref.enableAutoClasses; if ( enableAutoClasses === void 0 ) enableAutoClasses = false;
  2531. var classNames = ref.classNames; if ( classNames === void 0 ) classNames = {};
  2532. if (dictionary) {
  2533. Validator.updateDictionary(dictionary);
  2534. }
  2535. Validator.setLocale(locale);
  2536. Validator.setStrictMode(strict);
  2537. var options = {
  2538. locale: locale,
  2539. delay: delay,
  2540. dictionary: dictionary,
  2541. errorBagName: errorBagName,
  2542. fieldsBagName: fieldsBagName,
  2543. enableAutoClasses: enableAutoClasses,
  2544. classNames: assign({}, DEFAULT_CLASS_NAMES, classNames)
  2545. };
  2546. Vue.mixin(makeMixin(Vue, options));
  2547. Vue.directive('validate', makeDirective(options));
  2548. };
  2549. var index = {
  2550. install: install,
  2551. Validator: Validator,
  2552. ErrorBag: ErrorBag,
  2553. version: '2.0.0-beta.24'
  2554. };
  2555. return index;
  2556. })));