/** * vee-validate v2.1.0-beta.9 * (c) 2018 abdelrahman awad * @license mit */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.veevalidate = factory()); }(this, (function () { 'use strict'; var milliseconds_in_hour = 3600000; var milliseconds_in_minute = 60000; var default_additional_digits = 2; var patterns = { datetimedelimeter: /[t ]/, plaintime: /:/, // year tokens yy: /^(\d{2})$/, yyy: [ /^([+-]\d{2})$/, // 0 additional digits /^([+-]\d{3})$/, // 1 additional digit /^([+-]\d{4})$/ // 2 additional digits ], yyyy: /^(\d{4})/, yyyyy: [ /^([+-]\d{4})/, // 0 additional digits /^([+-]\d{5})/, // 1 additional digit /^([+-]\d{6})/ // 2 additional digits ], // date tokens mm: /^-(\d{2})$/, ddd: /^-?(\d{3})$/, mmdd: /^-?(\d{2})-?(\d{2})$/, www: /^-?w(\d{2})$/, wwwd: /^-?w(\d{2})-?(\d{1})$/, hh: /^(\d{2}([.,]\d*)?)$/, hhmm: /^(\d{2}):?(\d{2}([.,]\d*)?)$/, hhmmss: /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/, // timezone tokens timezone: /([z+-].*)$/, timezonez: /^(z)$/, timezonehh: /^([+-])(\d{2})$/, timezonehhmm: /^([+-])(\d{2}):?(\d{2})$/ }; /** * @name todate * @category common helpers * @summary convert the given argument to an instance of date. * * @description * convert the given argument to an instance of date. * * if the argument is an instance of date, the function returns its clone. * * if the argument is a number, it is treated as a timestamp. * * if an argument is a string, the function tries to parse it. * function accepts complete iso 8601 formats as well as partial implementations. * iso 8601: http://en.wikipedia.org/wiki/iso_8601 * * if the argument is null, it is treated as an invalid date. * * if all above fails, the function passes the given argument to date constructor. * * **note**: *all* date arguments passed to any *date-fns* function is processed by `todate`. * all *date-fns* functions will throw `rangeerror` if `options.additionaldigits` is not 0, 1, 2 or undefined. * * @param {*} argument - the value to convert * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - the additional number of digits in the extended year format * @returns {date} the parsed date in the local time zone * @throws {typeerror} 1 argument required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // convert string '2014-02-11t11:30:30' to date: * var result = todate('2014-02-11t11:30:30') * //=> tue feb 11 2014 11:30:30 * * @example * // convert string '+02014101' to date, * // if the additional number of digits in the extended year format is 1: * var result = todate('+02014101', {additionaldigits: 1}) * //=> fri apr 11 2014 00:00:00 */ function todate (argument, dirtyoptions) { if (arguments.length < 1) { throw new typeerror('1 argument required, but only ' + arguments.length + ' present') } if (argument === null) { return new date(nan) } var options = dirtyoptions || {}; var additionaldigits = options.additionaldigits === undefined ? default_additional_digits : number(options.additionaldigits); if (additionaldigits !== 2 && additionaldigits !== 1 && additionaldigits !== 0) { throw new rangeerror('additionaldigits must be 0, 1 or 2') } // clone the date if (argument instanceof date) { // prevent the date to lose the milliseconds when passed to new date() in ie10 return new date(argument.gettime()) } else if (typeof argument !== 'string') { return new date(argument) } var datestrings = splitdatestring(argument); var parseyearresult = parseyear(datestrings.date, additionaldigits); var year = parseyearresult.year; var restdatestring = parseyearresult.restdatestring; var date = parsedate(restdatestring, year); if (date) { var timestamp = date.gettime(); var time = 0; var offset; if (datestrings.time) { time = parsetime(datestrings.time); } if (datestrings.timezone) { offset = parsetimezone(datestrings.timezone); } else { // get offset accurate to hour in timezones that change offset offset = new date(timestamp + time).gettimezoneoffset(); offset = new date(timestamp + time + offset * milliseconds_in_minute).gettimezoneoffset(); } return new date(timestamp + time + offset * milliseconds_in_minute) } else { return new date(argument) } } function splitdatestring (datestring) { var datestrings = {}; var array = datestring.split(patterns.datetimedelimeter); var timestring; if (patterns.plaintime.test(array[0])) { datestrings.date = null; timestring = array[0]; } else { datestrings.date = array[0]; timestring = array[1]; } if (timestring) { var token = patterns.timezone.exec(timestring); if (token) { datestrings.time = timestring.replace(token[1], ''); datestrings.timezone = token[1]; } else { datestrings.time = timestring; } } return datestrings } function parseyear (datestring, additionaldigits) { var patternyyy = patterns.yyy[additionaldigits]; var patternyyyyy = patterns.yyyyy[additionaldigits]; var token; // yyyy or ±yyyyy token = patterns.yyyy.exec(datestring) || patternyyyyy.exec(datestring); if (token) { var yearstring = token[1]; return { year: parseint(yearstring, 10), restdatestring: datestring.slice(yearstring.length) } } // yy or ±yyy token = patterns.yy.exec(datestring) || patternyyy.exec(datestring); if (token) { var centurystring = token[1]; return { year: parseint(centurystring, 10) * 100, restdatestring: datestring.slice(centurystring.length) } } // invalid iso-formatted year return { year: null } } function parsedate (datestring, year) { // invalid iso-formatted year if (year === null) { return null } var token; var date; var month; var week; // yyyy if (datestring.length === 0) { date = new date(0); date.setutcfullyear(year); return date } // yyyy-mm token = patterns.mm.exec(datestring); if (token) { date = new date(0); month = parseint(token[1], 10) - 1; date.setutcfullyear(year, month); return date } // yyyy-ddd or yyyyddd token = patterns.ddd.exec(datestring); if (token) { date = new date(0); var dayofyear = parseint(token[1], 10); date.setutcfullyear(year, 0, dayofyear); return date } // yyyy-mm-dd or yyyymmdd token = patterns.mmdd.exec(datestring); if (token) { date = new date(0); month = parseint(token[1], 10) - 1; var day = parseint(token[2], 10); date.setutcfullyear(year, month, day); return date } // yyyy-www or yyyywww token = patterns.www.exec(datestring); if (token) { week = parseint(token[1], 10) - 1; return dayofisoyear(year, week) } // yyyy-www-d or yyyywwwd token = patterns.wwwd.exec(datestring); if (token) { week = parseint(token[1], 10) - 1; var dayofweek = parseint(token[2], 10) - 1; return dayofisoyear(year, week, dayofweek) } // invalid iso-formatted date return null } function parsetime (timestring) { var token; var hours; var minutes; // hh token = patterns.hh.exec(timestring); if (token) { hours = parsefloat(token[1].replace(',', '.')); return (hours % 24) * milliseconds_in_hour } // hh:mm or hhmm token = patterns.hhmm.exec(timestring); if (token) { hours = parseint(token[1], 10); minutes = parsefloat(token[2].replace(',', '.')); return (hours % 24) * milliseconds_in_hour + minutes * milliseconds_in_minute } // hh:mm:ss or hhmmss token = patterns.hhmmss.exec(timestring); if (token) { hours = parseint(token[1], 10); minutes = parseint(token[2], 10); var seconds = parsefloat(token[3].replace(',', '.')); return (hours % 24) * milliseconds_in_hour + minutes * milliseconds_in_minute + seconds * 1000 } // invalid iso-formatted time return null } function parsetimezone (timezonestring) { var token; var absoluteoffset; // z token = patterns.timezonez.exec(timezonestring); if (token) { return 0 } // ±hh token = patterns.timezonehh.exec(timezonestring); if (token) { absoluteoffset = parseint(token[2], 10) * 60; return (token[1] === '+') ? -absoluteoffset : absoluteoffset } // ±hh:mm or ±hhmm token = patterns.timezonehhmm.exec(timezonestring); if (token) { absoluteoffset = parseint(token[2], 10) * 60 + parseint(token[3], 10); return (token[1] === '+') ? -absoluteoffset : absoluteoffset } return 0 } function dayofisoyear (isoyear, week, day) { week = week || 0; day = day || 0; var date = new date(0); date.setutcfullyear(isoyear, 0, 4); var fourthofjanuaryday = date.getutcday() || 7; var diff = week * 7 + day + 1 - fourthofjanuaryday; date.setutcdate(date.getutcdate() + diff); return date } /** * @name addmilliseconds * @category millisecond helpers * @summary add the specified number of milliseconds to the given date. * * @description * add the specified number of milliseconds to the given date. * * @param {date|string|number} date - the date to be changed * @param {number} amount - the amount of milliseconds to be added * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {date} the new date with the milliseconds added * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // add 750 milliseconds to 10 july 2014 12:45:30.000: * var result = addmilliseconds(new date(2014, 6, 10, 12, 45, 30, 0), 750) * //=> thu jul 10 2014 12:45:30.750 */ function addmilliseconds (dirtydate, dirtyamount, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var timestamp = todate(dirtydate, dirtyoptions).gettime(); var amount = number(dirtyamount); return new date(timestamp + amount) } function cloneobject (dirtyobject) { dirtyobject = dirtyobject || {}; var object = {}; for (var property in dirtyobject) { if (dirtyobject.hasownproperty(property)) { object[property] = dirtyobject[property]; } } return object } var milliseconds_in_minute$2 = 60000; /** * @name addminutes * @category minute helpers * @summary add the specified number of minutes to the given date. * * @description * add the specified number of minutes to the given date. * * @param {date|string|number} date - the date to be changed * @param {number} amount - the amount of minutes to be added * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {date} the new date with the minutes added * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // add 30 minutes to 10 july 2014 12:00:00: * var result = addminutes(new date(2014, 6, 10, 12, 0), 30) * //=> thu jul 10 2014 12:30:00 */ function addminutes (dirtydate, dirtyamount, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var amount = number(dirtyamount); return addmilliseconds(dirtydate, amount * milliseconds_in_minute$2, dirtyoptions) } /** * @name isvalid * @category common helpers * @summary is the given date valid? * * @description * returns false if argument is invalid date and true otherwise. * argument is converted to date using `todate`. see [todate]{@link https://date-fns.org/docs/todate} * invalid date is a date, whose time value is nan. * * time value of date: http://es5.github.io/#x15.9.1.1 * * @param {*} date - the date to check * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {boolean} the date is valid * @throws {typeerror} 1 argument required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // for the valid date: * var result = isvalid(new date(2014, 1, 31)) * //=> true * * @example * // for the value, convertable into a date: * var result = isvalid('2014-02-31') * //=> true * * @example * // for the invalid date: * var result = isvalid(new date('')) * //=> false */ function isvalid (dirtydate, dirtyoptions) { if (arguments.length < 1) { throw new typeerror('1 argument required, but only ' + arguments.length + ' present') } var date = todate(dirtydate, dirtyoptions); return !isnan(date) } var formatdistancelocale = { lessthanxseconds: { one: 'less than a second', other: 'less than {{count}} seconds' }, xseconds: { one: '1 second', other: '{{count}} seconds' }, halfaminute: 'half a minute', lessthanxminutes: { one: 'less than a minute', other: 'less than {{count}} minutes' }, xminutes: { one: '1 minute', other: '{{count}} minutes' }, aboutxhours: { one: 'about 1 hour', other: 'about {{count}} hours' }, xhours: { one: '1 hour', other: '{{count}} hours' }, xdays: { one: '1 day', other: '{{count}} days' }, aboutxmonths: { one: 'about 1 month', other: 'about {{count}} months' }, xmonths: { one: '1 month', other: '{{count}} months' }, aboutxyears: { one: 'about 1 year', other: 'about {{count}} years' }, xyears: { one: '1 year', other: '{{count}} years' }, overxyears: { one: 'over 1 year', other: 'over {{count}} years' }, almostxyears: { one: 'almost 1 year', other: 'almost {{count}} years' } }; function formatdistance (token, count, options) { options = options || {}; var result; if (typeof formatdistancelocale[token] === 'string') { result = formatdistancelocale[token]; } else if (count === 1) { result = formatdistancelocale[token].one; } else { result = formatdistancelocale[token].other.replace('{{count}}', count); } if (options.addsuffix) { if (options.comparison > 0) { return 'in ' + result } else { return result + ' ago' } } return result } var tokenstobeshortedpattern = /mmmm|mm|dd|dddd/g; function buildshortlongformat (format) { return format.replace(tokenstobeshortedpattern, function (token) { return token.slice(1) }) } /** * @name buildformatlongfn * @category locale helpers * @summary build `formatlong` property for locale used by `format`, `formatrelative` and `parse` functions. * * @description * build `formatlong` property for locale used by `format`, `formatrelative` and `parse` functions. * returns a function which takes one of the following tokens as the argument: * `'lts'`, `'lt'`, `'l'`, `'ll'`, `'lll'`, `'l'`, `'ll'`, `'lll'`, `'llll'` * and returns a long format string written as `format` token strings. * see [format]{@link https://date-fns.org/docs/format} * * `'l'`, `'ll'`, `'lll'` and `'llll'` formats are built automatically * by shortening some of the tokens from corresponding unshortened formats * (e.g., if `ll` is `'mmmm dd yyyy'` then `ll` will be `mmm d yyyy`) * * @param {object} obj - the object with long formats written as `format` token strings * @param {string} obj.lt - time format: hours and minutes * @param {string} obj.lts - time format: hours, minutes and seconds * @param {string} obj.l - short date format: numeric day, month and year * @param {string} [obj.l] - short date format: numeric day, month and year (shortened) * @param {string} obj.ll - long date format: day, month in words, and year * @param {string} [obj.ll] - long date format: day, month in words, and year (shortened) * @param {string} obj.lll - long date and time format * @param {string} [obj.lll] - long date and time format (shortened) * @param {string} obj.llll - long date, time and weekday format * @param {string} [obj.llll] - long date, time and weekday format (shortened) * @returns {function} `formatlong` property of the locale * * @example * // for `en-us` locale: * locale.formatlong = buildformatlongfn({ * lt: 'h:mm aa', * lts: 'h:mm:ss aa', * l: 'mm/dd/yyyy', * ll: 'mmmm d yyyy', * lll: 'mmmm d yyyy h:mm aa', * llll: 'dddd, mmmm d yyyy h:mm aa' * }) */ function buildformatlongfn (obj) { var formatlonglocale = { lts: obj.lts, lt: obj.lt, l: obj.l, ll: obj.ll, lll: obj.lll, llll: obj.llll, l: obj.l || buildshortlongformat(obj.l), ll: obj.ll || buildshortlongformat(obj.ll), lll: obj.lll || buildshortlongformat(obj.lll), llll: obj.llll || buildshortlongformat(obj.llll) }; return function (token) { return formatlonglocale[token] } } var formatlong = buildformatlongfn({ lt: 'h:mm aa', lts: 'h:mm:ss aa', l: 'mm/dd/yyyy', ll: 'mmmm d yyyy', lll: 'mmmm d yyyy h:mm aa', llll: 'dddd, mmmm d yyyy h:mm aa' }); var formatrelativelocale = { lastweek: '[last] dddd [at] lt', yesterday: '[yesterday at] lt', today: '[today at] lt', tomorrow: '[tomorrow at] lt', nextweek: 'dddd [at] lt', other: 'l' }; function formatrelative (token, date, basedate, options) { return formatrelativelocale[token] } /** * @name buildlocalizefn * @category locale helpers * @summary build `localize.weekday`, `localize.month` and `localize.timeofday` properties for the locale. * * @description * build `localize.weekday`, `localize.month` and `localize.timeofday` properties for the locale * used by `format` function. * if no `type` is supplied to the options of the resulting function, `defaulttype` will be used (see example). * * `localize.weekday` function takes the weekday index as argument (0 - sunday). * `localize.month` takes the month index (0 - january). * `localize.timeofday` takes the hours. use `indexcallback` to convert them to an array index (see example). * * @param {object} values - the object with arrays of values * @param {string} defaulttype - the default type for the localize function * @param {function} [indexcallback] - the callback which takes the resulting function argument * and converts it into value array index * @returns {function} the resulting function * * @example * var timeofdayvalues = { * uppercase: ['am', 'pm'], * lowercase: ['am', 'pm'], * long: ['a.m.', 'p.m.'] * } * locale.localize.timeofday = buildlocalizefn(timeofdayvalues, 'long', function (hours) { * // 0 is a.m. array index, 1 is p.m. array index * return (hours / 12) >= 1 ? 1 : 0 * }) * locale.localize.timeofday(16, {type: 'uppercase'}) //=> 'pm' * locale.localize.timeofday(5) //=> 'a.m.' */ function buildlocalizefn (values, defaulttype, indexcallback) { return function (dirtyindex, dirtyoptions) { var options = dirtyoptions || {}; var type = options.type ? string(options.type) : defaulttype; var valuesarray = values[type] || values[defaulttype]; var index = indexcallback ? indexcallback(number(dirtyindex)) : number(dirtyindex); return valuesarray[index] } } /** * @name buildlocalizearrayfn * @category locale helpers * @summary build `localize.weekdays`, `localize.months` and `localize.timesofday` properties for the locale. * * @description * build `localize.weekdays`, `localize.months` and `localize.timesofday` properties for the locale. * if no `type` is supplied to the options of the resulting function, `defaulttype` will be used (see example). * * @param {object} values - the object with arrays of values * @param {string} defaulttype - the default type for the localize function * @returns {function} the resulting function * * @example * var weekdayvalues = { * narrow: ['su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'], * short: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], * long: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] * } * locale.localize.weekdays = buildlocalizearrayfn(weekdayvalues, 'long') * locale.localize.weekdays({type: 'narrow'}) //=> ['su', 'mo', ...] * locale.localize.weekdays() //=> ['sunday', 'monday', ...] */ function buildlocalizearrayfn (values, defaulttype) { return function (dirtyoptions) { var options = dirtyoptions || {}; var type = options.type ? string(options.type) : defaulttype; return values[type] || values[defaulttype] } } // note: in english, the names of days of the week and months are capitalized. // if you are making a new locale based on this one, check if the same is true for the language you're working on. // generally, formatted dates should look like they are in the middle of a sentence, // e.g. in spanish language the weekdays and months should be in the lowercase. var weekdayvalues = { narrow: ['su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'], short: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], long: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] }; var monthvalues = { short: ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'], long: ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] }; // `timeofday` is used to designate which part of the day it is, when used with 12-hour clock. // use the system which is used the most commonly in the locale. // for example, if the country doesn't use a.m./p.m., you can use `night`/`morning`/`afternoon`/`evening`: // // var timeofdayvalues = { // any: ['in the night', 'in the morning', 'in the afternoon', 'in the evening'] // } // // and later: // // var localize = { // // the callback takes the hours as the argument and returns the array index // timeofday: buildlocalizefn(timeofdayvalues, 'any', function (hours) { // if (hours >= 17) { // return 3 // } else if (hours >= 12) { // return 2 // } else if (hours >= 4) { // return 1 // } else { // return 0 // } // }), // timesofday: buildlocalizearrayfn(timeofdayvalues, 'any') // } var timeofdayvalues = { uppercase: ['am', 'pm'], lowercase: ['am', 'pm'], long: ['a.m.', 'p.m.'] }; function ordinalnumber (dirtynumber, dirtyoptions) { var number = number(dirtynumber); // if ordinal numbers depend on context, for example, // if they are different for different grammatical genders, // use `options.unit`: // // var options = dirtyoptions || {} // var unit = string(options.unit) // // where `unit` can be 'month', 'quarter', 'week', 'isoweek', 'dayofyear', // 'dayofmonth' or 'dayofweek' var rem100 = number % 100; if (rem100 > 20 || rem100 < 10) { switch (rem100 % 10) { case 1: return number + 'st' case 2: return number + 'nd' case 3: return number + 'rd' } } return number + 'th' } var localize = { ordinalnumber: ordinalnumber, weekday: buildlocalizefn(weekdayvalues, 'long'), weekdays: buildlocalizearrayfn(weekdayvalues, 'long'), month: buildlocalizefn(monthvalues, 'long'), months: buildlocalizearrayfn(monthvalues, 'long'), timeofday: buildlocalizefn(timeofdayvalues, 'long', function (hours) { return (hours / 12) >= 1 ? 1 : 0 }), timesofday: buildlocalizearrayfn(timeofdayvalues, 'long') }; /** * @name buildmatchfn * @category locale helpers * @summary build `match.weekdays`, `match.months` and `match.timesofday` properties for the locale. * * @description * build `match.weekdays`, `match.months` and `match.timesofday` properties for the locale used by `parse` function. * if no `type` is supplied to the options of the resulting function, `defaulttype` will be used (see example). * the result of the match function will be passed into corresponding parser function * (`match.weekday`, `match.month` or `match.timeofday` respectively. see `buildparsefn`). * * @param {object} values - the object with regexps * @param {string} defaulttype - the default type for the match function * @returns {function} the resulting function * * @example * var matchweekdayspatterns = { * narrow: /^(su|mo|tu|we|th|fr|sa)/i, * short: /^(sun|mon|tue|wed|thu|fri|sat)/i, * long: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i * } * locale.match.weekdays = buildmatchfn(matchweekdayspatterns, 'long') * locale.match.weekdays('sunday', {type: 'narrow'}) //=> ['su', 'su', ...] * locale.match.weekdays('sunday') //=> ['sunday', 'sunday', ...] */ function buildmatchfn (patterns, defaulttype) { return function (dirtystring, dirtyoptions) { var options = dirtyoptions || {}; var type = options.type ? string(options.type) : defaulttype; var pattern = patterns[type] || patterns[defaulttype]; var string = string(dirtystring); return string.match(pattern) } } /** * @name buildparsefn * @category locale helpers * @summary build `match.weekday`, `match.month` and `match.timeofday` properties for the locale. * * @description * build `match.weekday`, `match.month` and `match.timeofday` properties for the locale used by `parse` function. * the argument of the resulting function is the result of the corresponding match function * (`match.weekdays`, `match.months` or `match.timesofday` respectively. see `buildmatchfn`). * * @param {object} values - the object with arrays of regexps * @param {string} defaulttype - the default type for the parser function * @returns {function} the resulting function * * @example * var parseweekdaypatterns = { * any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] * } * locale.match.weekday = buildparsefn(matchweekdayspatterns, 'long') * var matchresult = locale.match.weekdays('friday') * locale.match.weekday(matchresult) //=> 5 */ function buildparsefn (patterns, defaulttype) { return function (matchresult, dirtyoptions) { var options = dirtyoptions || {}; var type = options.type ? string(options.type) : defaulttype; var patternsarray = patterns[type] || patterns[defaulttype]; var string = matchresult[1]; return patternsarray.findindex(function (pattern) { return pattern.test(string) }) } } /** * @name buildmatchpatternfn * @category locale helpers * @summary build match function from a single regexp. * * @description * build match function from a single regexp. * usually used for building `match.ordinalnumbers` property of the locale. * * @param {object} pattern - the regexp * @returns {function} the resulting function * * @example * locale.match.ordinalnumbers = buildmatchpatternfn(/^(\d+)(th|st|nd|rd)?/i) * locale.match.ordinalnumbers('3rd') //=> ['3rd', '3', 'rd', ...] */ function buildmatchpatternfn (pattern) { return function (dirtystring) { var string = string(dirtystring); return string.match(pattern) } } /** * @name parsedecimal * @category locale helpers * @summary parses the match result into decimal number. * * @description * parses the match result into decimal number. * uses the string matched with the first set of parentheses of match regexp. * * @param {array} matchresult - the object returned by matching function * @returns {number} the parsed value * * @example * locale.match = { * ordinalnumbers: (dirtystring) { * return string(dirtystring).match(/^(\d+)(th|st|nd|rd)?/i) * }, * ordinalnumber: parsedecimal * } */ function parsedecimal (matchresult) { return parseint(matchresult[1], 10) } var matchordinalnumberspattern = /^(\d+)(th|st|nd|rd)?/i; var matchweekdayspatterns = { narrow: /^(su|mo|tu|we|th|fr|sa)/i, short: /^(sun|mon|tue|wed|thu|fri|sat)/i, long: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i }; var parseweekdaypatterns = { any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] }; var matchmonthspatterns = { short: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, long: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i }; var parsemonthpatterns = { any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] }; // `timeofday` is used to designate which part of the day it is, when used with 12-hour clock. // use the system which is used the most commonly in the locale. // for example, if the country doesn't use a.m./p.m., you can use `night`/`morning`/`afternoon`/`evening`: // // var matchtimesofdaypatterns = { // long: /^((in the)? (night|morning|afternoon|evening?))/i // } // // var parsetimeofdaypatterns = { // any: [/(night|morning)/i, /(afternoon|evening)/i] // } var matchtimesofdaypatterns = { short: /^(am|pm)/i, long: /^([ap]\.?\s?m\.?)/i }; var parsetimeofdaypatterns = { any: [/^a/i, /^p/i] }; var match = { ordinalnumbers: buildmatchpatternfn(matchordinalnumberspattern), ordinalnumber: parsedecimal, weekdays: buildmatchfn(matchweekdayspatterns, 'long'), weekday: buildparsefn(parseweekdaypatterns, 'any'), months: buildmatchfn(matchmonthspatterns, 'long'), month: buildparsefn(parsemonthpatterns, 'any'), timesofday: buildmatchfn(matchtimesofdaypatterns, 'long'), timeofday: buildparsefn(parsetimeofdaypatterns, 'any') }; /** * @type {locale} * @category locales * @summary english locale (united states). * @language english * @iso-639-2 eng */ var locale = { formatdistance: formatdistance, formatlong: formatlong, formatrelative: formatrelative, localize: localize, match: match, options: { weekstartson: 0 /* sunday */, firstweekcontainsdate: 1 } }; var milliseconds_in_day$1 = 86400000; // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function getutcdayofyear (dirtydate, dirtyoptions) { var date = todate(dirtydate, dirtyoptions); var timestamp = date.gettime(); date.setutcmonth(0, 1); date.setutchours(0, 0, 0, 0); var startofyeartimestamp = date.gettime(); var difference = timestamp - startofyeartimestamp; return math.floor(difference / milliseconds_in_day$1) + 1 } // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function startofutcisoweek (dirtydate, dirtyoptions) { var weekstartson = 1; var date = todate(dirtydate, dirtyoptions); var day = date.getutcday(); var diff = (day < weekstartson ? 7 : 0) + day - weekstartson; date.setutcdate(date.getutcdate() - diff); date.setutchours(0, 0, 0, 0); return date } // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function getutcisoweekyear (dirtydate, dirtyoptions) { var date = todate(dirtydate, dirtyoptions); var year = date.getutcfullyear(); var fourthofjanuaryofnextyear = new date(0); fourthofjanuaryofnextyear.setutcfullyear(year + 1, 0, 4); fourthofjanuaryofnextyear.setutchours(0, 0, 0, 0); var startofnextyear = startofutcisoweek(fourthofjanuaryofnextyear, dirtyoptions); var fourthofjanuaryofthisyear = new date(0); fourthofjanuaryofthisyear.setutcfullyear(year, 0, 4); fourthofjanuaryofthisyear.setutchours(0, 0, 0, 0); var startofthisyear = startofutcisoweek(fourthofjanuaryofthisyear, dirtyoptions); if (date.gettime() >= startofnextyear.gettime()) { return year + 1 } else if (date.gettime() >= startofthisyear.gettime()) { return year } else { return year - 1 } } // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function startofutcisoweekyear (dirtydate, dirtyoptions) { var year = getutcisoweekyear(dirtydate, dirtyoptions); var fourthofjanuary = new date(0); fourthofjanuary.setutcfullyear(year, 0, 4); fourthofjanuary.setutchours(0, 0, 0, 0); var date = startofutcisoweek(fourthofjanuary, dirtyoptions); return date } var milliseconds_in_week$2 = 604800000; // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function getutcisoweek (dirtydate, dirtyoptions) { var date = todate(dirtydate, dirtyoptions); var diff = startofutcisoweek(date, dirtyoptions).gettime() - startofutcisoweekyear(date, dirtyoptions).gettime(); // round the number of days to the nearest integer // because the number of milliseconds in a week is not constant // (e.g. it's different in the week of the daylight saving time clock shift) return math.round(diff / milliseconds_in_week$2) + 1 } var formatters = { // month: 1, 2, ..., 12 'm': function (date) { return date.getutcmonth() + 1 }, // month: 1st, 2nd, ..., 12th 'mo': function (date, options) { var month = date.getutcmonth() + 1; return options.locale.localize.ordinalnumber(month, {unit: 'month'}) }, // month: 01, 02, ..., 12 'mm': function (date) { return addleadingzeros(date.getutcmonth() + 1, 2) }, // month: jan, feb, ..., dec 'mmm': function (date, options) { return options.locale.localize.month(date.getutcmonth(), {type: 'short'}) }, // month: january, february, ..., december 'mmmm': function (date, options) { return options.locale.localize.month(date.getutcmonth(), {type: 'long'}) }, // quarter: 1, 2, 3, 4 'q': function (date) { return math.ceil((date.getutcmonth() + 1) / 3) }, // quarter: 1st, 2nd, 3rd, 4th 'qo': function (date, options) { var quarter = math.ceil((date.getutcmonth() + 1) / 3); return options.locale.localize.ordinalnumber(quarter, {unit: 'quarter'}) }, // day of month: 1, 2, ..., 31 'd': function (date) { return date.getutcdate() }, // day of month: 1st, 2nd, ..., 31st 'do': function (date, options) { return options.locale.localize.ordinalnumber(date.getutcdate(), {unit: 'dayofmonth'}) }, // day of month: 01, 02, ..., 31 'dd': function (date) { return addleadingzeros(date.getutcdate(), 2) }, // day of year: 1, 2, ..., 366 'ddd': function (date) { return getutcdayofyear(date) }, // day of year: 1st, 2nd, ..., 366th 'dddo': function (date, options) { return options.locale.localize.ordinalnumber(getutcdayofyear(date), {unit: 'dayofyear'}) }, // day of year: 001, 002, ..., 366 'dddd': function (date) { return addleadingzeros(getutcdayofyear(date), 3) }, // day of week: su, mo, ..., sa 'dd': function (date, options) { return options.locale.localize.weekday(date.getutcday(), {type: 'narrow'}) }, // day of week: sun, mon, ..., sat 'ddd': function (date, options) { return options.locale.localize.weekday(date.getutcday(), {type: 'short'}) }, // day of week: sunday, monday, ..., saturday 'dddd': function (date, options) { return options.locale.localize.weekday(date.getutcday(), {type: 'long'}) }, // day of week: 0, 1, ..., 6 'd': function (date) { return date.getutcday() }, // day of week: 0th, 1st, 2nd, ..., 6th 'do': function (date, options) { return options.locale.localize.ordinalnumber(date.getutcday(), {unit: 'dayofweek'}) }, // day of iso week: 1, 2, ..., 7 'e': function (date) { return date.getutcday() || 7 }, // iso week: 1, 2, ..., 53 'w': function (date) { return getutcisoweek(date) }, // iso week: 1st, 2nd, ..., 53th 'wo': function (date, options) { return options.locale.localize.ordinalnumber(getutcisoweek(date), {unit: 'isoweek'}) }, // iso week: 01, 02, ..., 53 'ww': function (date) { return addleadingzeros(getutcisoweek(date), 2) }, // year: 00, 01, ..., 99 'yy': function (date) { return addleadingzeros(date.getutcfullyear(), 4).substr(2) }, // year: 1900, 1901, ..., 2099 'yyyy': function (date) { return addleadingzeros(date.getutcfullyear(), 4) }, // iso week-numbering year: 00, 01, ..., 99 'gg': function (date) { return string(getutcisoweekyear(date)).substr(2) }, // iso week-numbering year: 1900, 1901, ..., 2099 'gggg': function (date) { return getutcisoweekyear(date) }, // hour: 0, 1, ... 23 'h': function (date) { return date.getutchours() }, // hour: 00, 01, ..., 23 'hh': function (date) { return addleadingzeros(date.getutchours(), 2) }, // hour: 1, 2, ..., 12 'h': function (date) { var hours = date.getutchours(); if (hours === 0) { return 12 } else if (hours > 12) { return hours % 12 } else { return hours } }, // hour: 01, 02, ..., 12 'hh': function (date) { return addleadingzeros(formatters['h'](date), 2) }, // minute: 0, 1, ..., 59 'm': function (date) { return date.getutcminutes() }, // minute: 00, 01, ..., 59 'mm': function (date) { return addleadingzeros(date.getutcminutes(), 2) }, // second: 0, 1, ..., 59 's': function (date) { return date.getutcseconds() }, // second: 00, 01, ..., 59 'ss': function (date) { return addleadingzeros(date.getutcseconds(), 2) }, // 1/10 of second: 0, 1, ..., 9 's': function (date) { return math.floor(date.getutcmilliseconds() / 100) }, // 1/100 of second: 00, 01, ..., 99 'ss': function (date) { return addleadingzeros(math.floor(date.getutcmilliseconds() / 10), 2) }, // millisecond: 000, 001, ..., 999 'sss': function (date) { return addleadingzeros(date.getutcmilliseconds(), 3) }, // timezone: -01:00, +00:00, ... +12:00 'z': function (date, options) { var originaldate = options._originaldate || date; return formattimezone(originaldate.gettimezoneoffset(), ':') }, // timezone: -0100, +0000, ... +1200 'zz': function (date, options) { var originaldate = options._originaldate || date; return formattimezone(originaldate.gettimezoneoffset()) }, // seconds timestamp: 512969520 'x': function (date, options) { var originaldate = options._originaldate || date; return math.floor(originaldate.gettime() / 1000) }, // milliseconds timestamp: 512969520900 'x': function (date, options) { var originaldate = options._originaldate || date; return originaldate.gettime() }, // am, pm 'a': function (date, options) { return options.locale.localize.timeofday(date.getutchours(), {type: 'uppercase'}) }, // am, pm 'a': function (date, options) { return options.locale.localize.timeofday(date.getutchours(), {type: 'lowercase'}) }, // a.m., p.m. 'aa': function (date, options) { return options.locale.localize.timeofday(date.getutchours(), {type: 'long'}) } }; function formattimezone (offset, delimeter) { delimeter = delimeter || ''; var sign = offset > 0 ? '-' : '+'; var absoffset = math.abs(offset); var hours = math.floor(absoffset / 60); var minutes = absoffset % 60; return sign + addleadingzeros(hours, 2) + delimeter + addleadingzeros(minutes, 2) } function addleadingzeros (number, targetlength) { var output = math.abs(number).tostring(); while (output.length < targetlength) { output = '0' + output; } return output } // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function addutcminutes (dirtydate, dirtyamount, dirtyoptions) { var date = todate(dirtydate, dirtyoptions); var amount = number(dirtyamount); date.setutcminutes(date.getutcminutes() + amount); return date } var longformattingtokensregexp = /(\[[^[]*])|(\\)?(lts|lt|llll|lll|ll|l|llll|lll|ll|l)/g; var defaultformattingtokensregexp = /(\[[^[]*])|(\\)?(x|ss|s|mm|m|hh|h|do|dddd|ddd|dd|d|aa|a|zz|z|yyyy|yy|x|wo|ww|w|sss|ss|s|qo|q|mo|mmmm|mmm|mm|m|hh|h|gggg|gg|e|do|dddo|dddd|ddd|dd|d|a|.)/g; /** * @name format * @category common helpers * @summary format the date. * * @description * return the formatted date string in the given format. * * accepted tokens: * | unit | token | result examples | * |-------------------------|-------|----------------------------------| * | month | m | 1, 2, ..., 12 | * | | mo | 1st, 2nd, ..., 12th | * | | mm | 01, 02, ..., 12 | * | | mmm | jan, feb, ..., dec | * | | mmmm | january, february, ..., december | * | quarter | q | 1, 2, 3, 4 | * | | qo | 1st, 2nd, 3rd, 4th | * | day of month | d | 1, 2, ..., 31 | * | | do | 1st, 2nd, ..., 31st | * | | dd | 01, 02, ..., 31 | * | day of year | ddd | 1, 2, ..., 366 | * | | dddo | 1st, 2nd, ..., 366th | * | | dddd | 001, 002, ..., 366 | * | day of week | d | 0, 1, ..., 6 | * | | do | 0th, 1st, ..., 6th | * | | dd | su, mo, ..., sa | * | | ddd | sun, mon, ..., sat | * | | dddd | sunday, monday, ..., saturday | * | day of iso week | e | 1, 2, ..., 7 | * | iso week | w | 1, 2, ..., 53 | * | | wo | 1st, 2nd, ..., 53rd | * | | ww | 01, 02, ..., 53 | * | year | yy | 00, 01, ..., 99 | * | | yyyy | 1900, 1901, ..., 2099 | * | iso week-numbering year | gg | 00, 01, ..., 99 | * | | gggg | 1900, 1901, ..., 2099 | * | am/pm | a | am, pm | * | | a | am, pm | * | | aa | a.m., p.m. | * | hour | h | 0, 1, ... 23 | * | | hh | 00, 01, ... 23 | * | | h | 1, 2, ..., 12 | * | | hh | 01, 02, ..., 12 | * | minute | m | 0, 1, ..., 59 | * | | mm | 00, 01, ..., 59 | * | second | s | 0, 1, ..., 59 | * | | ss | 00, 01, ..., 59 | * | 1/10 of second | s | 0, 1, ..., 9 | * | 1/100 of second | ss | 00, 01, ..., 99 | * | millisecond | sss | 000, 001, ..., 999 | * | timezone | z | -01:00, +00:00, ... +12:00 | * | | zz | -0100, +0000, ..., +1200 | * | seconds timestamp | x | 512969520 | * | milliseconds timestamp | x | 512969520900 | * | long format | lt | 05:30 a.m. | * | | lts | 05:30:15 a.m. | * | | l | 07/02/1995 | * | | l | 7/2/1995 | * | | ll | july 2 1995 | * | | ll | jul 2 1995 | * | | lll | july 2 1995 05:30 a.m. | * | | lll | jul 2 1995 05:30 a.m. | * | | llll | sunday, july 2 1995 05:30 a.m. | * | | llll | sun, jul 2 1995 05:30 a.m. | * * the characters wrapped in square brackets are escaped. * * the result may vary by locale. * * @param {date|string|number} date - the original date * @param {string} format - the string of tokens * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @param {locale} [options.locale=defaultlocale] - the locale object. see [locale]{@link https://date-fns.org/docs/locale} * @returns {string} the formatted date string * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * @throws {rangeerror} `options.locale` must contain `localize` property * @throws {rangeerror} `options.locale` must contain `formatlong` property * * @example * // represent 11 february 2014 in middle-endian format: * var result = format( * new date(2014, 1, 11), * 'mm/dd/yyyy' * ) * //=> '02/11/2014' * * @example * // represent 2 july 2014 in esperanto: * import { eolocale } from 'date-fns/locale/eo' * var result = format( * new date(2014, 6, 2), * 'do [de] mmmm yyyy', * {locale: eolocale} * ) * //=> '2-a de julio 2014' */ function format (dirtydate, dirtyformatstr, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var formatstr = string(dirtyformatstr); var options = dirtyoptions || {}; var locale$$1 = options.locale || locale; if (!locale$$1.localize) { throw new rangeerror('locale must contain localize property') } if (!locale$$1.formatlong) { throw new rangeerror('locale must contain formatlong property') } var localeformatters = locale$$1.formatters || {}; var formattingtokensregexp = locale$$1.formattingtokensregexp || defaultformattingtokensregexp; var formatlong = locale$$1.formatlong; var originaldate = todate(dirtydate, options); if (!isvalid(originaldate, options)) { return 'invalid date' } // convert the date in system timezone to the same date in utc+00:00 timezone. // this ensures that when utc functions will be implemented, locales will be compatible with them. // see an issue about utc functions: https://github.com/date-fns/date-fns/issues/376 var timezoneoffset = originaldate.gettimezoneoffset(); var utcdate = addutcminutes(originaldate, -timezoneoffset, options); var formatteroptions = cloneobject(options); formatteroptions.locale = locale$$1; formatteroptions.formatters = formatters; // when utc functions will be implemented, options._originaldate will likely be a part of public api. // right now, please don't use it in locales. if you have to use an original date, // please restore it from `date`, adding a timezone offset to it. formatteroptions._originaldate = originaldate; var result = formatstr .replace(longformattingtokensregexp, function (substring) { if (substring[0] === '[') { return substring } if (substring[0] === '\\') { return cleanescapedstring(substring) } return formatlong(substring) }) .replace(formattingtokensregexp, function (substring) { var formatter = localeformatters[substring] || formatters[substring]; if (formatter) { return formatter(utcdate, formatteroptions) } else { return cleanescapedstring(substring) } }); return result } function cleanescapedstring (input) { if (input.match(/\[[\s\s]/)) { return input.replace(/^\[|]$/g, '') } return input.replace(/\\/g, '') } /** * @name subminutes * @category minute helpers * @summary subtract the specified number of minutes from the given date. * * @description * subtract the specified number of minutes from the given date. * * @param {date|string|number} date - the date to be changed * @param {number} amount - the amount of minutes to be subtracted * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {date} the new date with the mintues subtracted * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // subtract 30 minutes from 10 july 2014 12:00:00: * var result = subminutes(new date(2014, 6, 10, 12, 0), 30) * //=> thu jul 10 2014 11:30:00 */ function subminutes (dirtydate, dirtyamount, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var amount = number(dirtyamount); return addminutes(dirtydate, -amount, dirtyoptions) } /** * @name isafter * @category common helpers * @summary is the first date after the second one? * * @description * is the first date after the second one? * * @param {date|string|number} date - the date that should be after the other one to return true * @param {date|string|number} datetocompare - the date to compare with * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {boolean} the first date is after the second date * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // is 10 july 1989 after 11 february 1987? * var result = isafter(new date(1989, 6, 10), new date(1987, 1, 11)) * //=> true */ function isafter (dirtydate, dirtydatetocompare, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var date = todate(dirtydate, dirtyoptions); var datetocompare = todate(dirtydatetocompare, dirtyoptions); return date.gettime() > datetocompare.gettime() } /** * @name isbefore * @category common helpers * @summary is the first date before the second one? * * @description * is the first date before the second one? * * @param {date|string|number} date - the date that should be before the other one to return true * @param {date|string|number} datetocompare - the date to compare with * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {boolean} the first date is before the second date * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // is 10 july 1989 before 11 february 1987? * var result = isbefore(new date(1989, 6, 10), new date(1987, 1, 11)) * //=> false */ function isbefore (dirtydate, dirtydatetocompare, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var date = todate(dirtydate, dirtyoptions); var datetocompare = todate(dirtydatetocompare, dirtyoptions); return date.gettime() < datetocompare.gettime() } /** * @name isequal * @category common helpers * @summary are the given dates equal? * * @description * are the given dates equal? * * @param {date|string|number} dateleft - the first date to compare * @param {date|string|number} dateright - the second date to compare * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @returns {boolean} the dates are equal * @throws {typeerror} 2 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * * @example * // are 2 july 2014 06:30:45.000 and 2 july 2014 06:30:45.500 equal? * var result = isequal( * new date(2014, 6, 2, 6, 30, 45, 0) * new date(2014, 6, 2, 6, 30, 45, 500) * ) * //=> false */ function isequal (dirtyleftdate, dirtyrightdate, dirtyoptions) { if (arguments.length < 2) { throw new typeerror('2 arguments required, but only ' + arguments.length + ' present') } var dateleft = todate(dirtyleftdate, dirtyoptions); var dateright = todate(dirtyrightdate, dirtyoptions); return dateleft.gettime() === dateright.gettime() } var patterns$1 = { 'm': /^(1[0-2]|0?\d)/, // 0 to 12 'd': /^(3[0-1]|[0-2]?\d)/, // 0 to 31 'ddd': /^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/, // 0 to 366 'w': /^(5[0-3]|[0-4]?\d)/, // 0 to 53 'yyyy': /^(\d{1,4})/, // 0 to 9999 'h': /^(2[0-3]|[0-1]?\d)/, // 0 to 23 'm': /^([0-5]?\d)/, // 0 to 59 'z': /^([+-])(\d{2}):(\d{2})/, 'zz': /^([+-])(\d{2})(\d{2})/, singledigit: /^(\d)/, twodigits: /^(\d{2})/, threedigits: /^(\d{3})/, fourdigits: /^(\d{4})/, anydigits: /^(\d+)/ }; function parsedecimal$1 (matchresult) { return parseint(matchresult[1], 10) } var parsers = { // year: 00, 01, ..., 99 'yy': { unit: 'twodigityear', match: patterns$1.twodigits, parse: function (matchresult) { return parsedecimal$1(matchresult) } }, // year: 1900, 1901, ..., 2099 'yyyy': { unit: 'year', match: patterns$1.yyyy, parse: parsedecimal$1 }, // iso week-numbering year: 00, 01, ..., 99 'gg': { unit: 'isoyear', match: patterns$1.twodigits, parse: function (matchresult) { return parsedecimal$1(matchresult) + 1900 } }, // iso week-numbering year: 1900, 1901, ..., 2099 'gggg': { unit: 'isoyear', match: patterns$1.yyyy, parse: parsedecimal$1 }, // quarter: 1, 2, 3, 4 'q': { unit: 'quarter', match: patterns$1.singledigit, parse: parsedecimal$1 }, // ordinal quarter 'qo': { unit: 'quarter', match: function (string, options) { return options.locale.match.ordinalnumbers(string, {unit: 'quarter'}) }, parse: function (matchresult, options) { return options.locale.match.ordinalnumber(matchresult, {unit: 'quarter'}) } }, // month: 1, 2, ..., 12 'm': { unit: 'month', match: patterns$1.m, parse: function (matchresult) { return parsedecimal$1(matchresult) - 1 } }, // ordinal month 'mo': { unit: 'month', match: function (string, options) { return options.locale.match.ordinalnumbers(string, {unit: 'month'}) }, parse: function (matchresult, options) { return options.locale.match.ordinalnumber(matchresult, {unit: 'month'}) - 1 } }, // month: 01, 02, ..., 12 'mm': { unit: 'month', match: patterns$1.twodigits, parse: function (matchresult) { return parsedecimal$1(matchresult) - 1 } }, // month: jan, feb, ..., dec 'mmm': { unit: 'month', match: function (string, options) { return options.locale.match.months(string, {type: 'short'}) }, parse: function (matchresult, options) { return options.locale.match.month(matchresult, {type: 'short'}) } }, // month: january, february, ..., december 'mmmm': { unit: 'month', match: function (string, options) { return options.locale.match.months(string, {type: 'long'}) || options.locale.match.months(string, {type: 'short'}) }, parse: function (matchresult, options) { var parseresult = options.locale.match.month(matchresult, {type: 'long'}); if (parseresult == null) { parseresult = options.locale.match.month(matchresult, {type: 'short'}); } return parseresult } }, // iso week: 1, 2, ..., 53 'w': { unit: 'isoweek', match: patterns$1.w, parse: parsedecimal$1 }, // ordinal iso week 'wo': { unit: 'isoweek', match: function (string, options) { return options.locale.match.ordinalnumbers(string, {unit: 'isoweek'}) }, parse: function (matchresult, options) { return options.locale.match.ordinalnumber(matchresult, {unit: 'isoweek'}) } }, // iso week: 01, 02, ..., 53 'ww': { unit: 'isoweek', match: patterns$1.twodigits, parse: parsedecimal$1 }, // day of week: 0, 1, ..., 6 'd': { unit: 'dayofweek', match: patterns$1.singledigit, parse: parsedecimal$1 }, // ordinal day of week 'do': { unit: 'dayofweek', match: function (string, options) { return options.locale.match.ordinalnumbers(string, {unit: 'dayofweek'}) }, parse: function (matchresult, options) { return options.locale.match.ordinalnumber(matchresult, {unit: 'dayofweek'}) } }, // day of week: su, mo, ..., sa 'dd': { unit: 'dayofweek', match: function (string, options) { return options.locale.match.weekdays(string, {type: 'narrow'}) }, parse: function (matchresult, options) { return options.locale.match.weekday(matchresult, {type: 'narrow'}) } }, // day of week: sun, mon, ..., sat 'ddd': { unit: 'dayofweek', match: function (string, options) { return options.locale.match.weekdays(string, {type: 'short'}) || options.locale.match.weekdays(string, {type: 'narrow'}) }, parse: function (matchresult, options) { var parseresult = options.locale.match.weekday(matchresult, {type: 'short'}); if (parseresult == null) { parseresult = options.locale.match.weekday(matchresult, {type: 'narrow'}); } return parseresult } }, // day of week: sunday, monday, ..., saturday 'dddd': { unit: 'dayofweek', match: function (string, options) { return options.locale.match.weekdays(string, {type: 'long'}) || options.locale.match.weekdays(string, {type: 'short'}) || options.locale.match.weekdays(string, {type: 'narrow'}) }, parse: function (matchresult, options) { var parseresult = options.locale.match.weekday(matchresult, {type: 'long'}); if (parseresult == null) { parseresult = options.locale.match.weekday(matchresult, {type: 'short'}); if (parseresult == null) { parseresult = options.locale.match.weekday(matchresult, {type: 'narrow'}); } } return parseresult } }, // day of iso week: 1, 2, ..., 7 'e': { unit: 'dayofisoweek', match: patterns$1.singledigit, parse: function (matchresult) { return parsedecimal$1(matchresult) } }, // day of month: 1, 2, ..., 31 'd': { unit: 'dayofmonth', match: patterns$1.d, parse: parsedecimal$1 }, // ordinal day of month 'do': { unit: 'dayofmonth', match: function (string, options) { return options.locale.match.ordinalnumbers(string, {unit: 'dayofmonth'}) }, parse: function (matchresult, options) { return options.locale.match.ordinalnumber(matchresult, {unit: 'dayofmonth'}) } }, // day of month: 01, 02, ..., 31 'dd': { unit: 'dayofmonth', match: patterns$1.twodigits, parse: parsedecimal$1 }, // day of year: 1, 2, ..., 366 'ddd': { unit: 'dayofyear', match: patterns$1.ddd, parse: parsedecimal$1 }, // ordinal day of year 'dddo': { unit: 'dayofyear', match: function (string, options) { return options.locale.match.ordinalnumbers(string, {unit: 'dayofyear'}) }, parse: function (matchresult, options) { return options.locale.match.ordinalnumber(matchresult, {unit: 'dayofyear'}) } }, // day of year: 001, 002, ..., 366 'dddd': { unit: 'dayofyear', match: patterns$1.threedigits, parse: parsedecimal$1 }, // am, pm 'a': { unit: 'timeofday', match: function (string, options) { return options.locale.match.timesofday(string, {type: 'short'}) }, parse: function (matchresult, options) { return options.locale.match.timeofday(matchresult, {type: 'short'}) } }, // a.m., p.m. 'aa': { unit: 'timeofday', match: function (string, options) { return options.locale.match.timesofday(string, {type: 'long'}) || options.locale.match.timesofday(string, {type: 'short'}) }, parse: function (matchresult, options) { var parseresult = options.locale.match.timeofday(matchresult, {type: 'long'}); if (parseresult == null) { parseresult = options.locale.match.timeofday(matchresult, {type: 'short'}); } return parseresult } }, // hour: 0, 1, ... 23 'h': { unit: 'hours', match: patterns$1.h, parse: parsedecimal$1 }, // hour: 00, 01, ..., 23 'hh': { unit: 'hours', match: patterns$1.twodigits, parse: parsedecimal$1 }, // hour: 1, 2, ..., 12 'h': { unit: 'timeofdayhours', match: patterns$1.m, parse: parsedecimal$1 }, // hour: 01, 02, ..., 12 'hh': { unit: 'timeofdayhours', match: patterns$1.twodigits, parse: parsedecimal$1 }, // minute: 0, 1, ..., 59 'm': { unit: 'minutes', match: patterns$1.m, parse: parsedecimal$1 }, // minute: 00, 01, ..., 59 'mm': { unit: 'minutes', match: patterns$1.twodigits, parse: parsedecimal$1 }, // second: 0, 1, ..., 59 's': { unit: 'seconds', match: patterns$1.m, parse: parsedecimal$1 }, // second: 00, 01, ..., 59 'ss': { unit: 'seconds', match: patterns$1.twodigits, parse: parsedecimal$1 }, // 1/10 of second: 0, 1, ..., 9 's': { unit: 'milliseconds', match: patterns$1.singledigit, parse: function (matchresult) { return parsedecimal$1(matchresult) * 100 } }, // 1/100 of second: 00, 01, ..., 99 'ss': { unit: 'milliseconds', match: patterns$1.twodigits, parse: function (matchresult) { return parsedecimal$1(matchresult) * 10 } }, // millisecond: 000, 001, ..., 999 'sss': { unit: 'milliseconds', match: patterns$1.threedigits, parse: parsedecimal$1 }, // timezone: -01:00, +00:00, ... +12:00 'z': { unit: 'timezone', match: patterns$1.z, parse: function (matchresult) { var sign = matchresult[1]; var hours = parseint(matchresult[2], 10); var minutes = parseint(matchresult[3], 10); var absoluteoffset = hours * 60 + minutes; return (sign === '+') ? absoluteoffset : -absoluteoffset } }, // timezone: -0100, +0000, ... +1200 'zz': { unit: 'timezone', match: patterns$1.zz, parse: function (matchresult) { var sign = matchresult[1]; var hours = parseint(matchresult[2], 10); var minutes = parseint(matchresult[3], 10); var absoluteoffset = hours * 60 + minutes; return (sign === '+') ? absoluteoffset : -absoluteoffset } }, // seconds timestamp: 512969520 'x': { unit: 'timestamp', match: patterns$1.anydigits, parse: function (matchresult) { return parsedecimal$1(matchresult) * 1000 } }, // milliseconds timestamp: 512969520900 'x': { unit: 'timestamp', match: patterns$1.anydigits, parse: parsedecimal$1 } }; parsers['a'] = parsers['a']; // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function setutcday (dirtydate, dirtyday, dirtyoptions) { var options = dirtyoptions || {}; var locale = options.locale; var localeweekstartson = locale && locale.options && locale.options.weekstartson; var defaultweekstartson = localeweekstartson === undefined ? 0 : number(localeweekstartson); var weekstartson = options.weekstartson === undefined ? defaultweekstartson : number(options.weekstartson); // test if weekstartson is between 0 and 6 _and_ is not nan if (!(weekstartson >= 0 && weekstartson <= 6)) { throw new rangeerror('weekstartson must be between 0 and 6 inclusively') } var date = todate(dirtydate, dirtyoptions); var day = number(dirtyday); var currentday = date.getutcday(); var remainder = day % 7; var dayindex = (remainder + 7) % 7; var diff = (dayindex < weekstartson ? 7 : 0) + day - currentday; date.setutcdate(date.getutcdate() + diff); return date } // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function setutcisoday (dirtydate, dirtyday, dirtyoptions) { var day = number(dirtyday); if (day % 7 === 0) { day = day - 7; } var weekstartson = 1; var date = todate(dirtydate, dirtyoptions); var currentday = date.getutcday(); var remainder = day % 7; var dayindex = (remainder + 7) % 7; var diff = (dayindex < weekstartson ? 7 : 0) + day - currentday; date.setutcdate(date.getutcdate() + diff); return date } // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function setutcisoweek (dirtydate, dirtyisoweek, dirtyoptions) { var date = todate(dirtydate, dirtyoptions); var isoweek = number(dirtyisoweek); var diff = getutcisoweek(date, dirtyoptions) - isoweek; date.setutcdate(date.getutcdate() - diff * 7); return date } var milliseconds_in_day$3 = 86400000; // this function will be a part of public api when utc function will be implemented. // see issue: https://github.com/date-fns/date-fns/issues/376 function setutcisoweekyear (dirtydate, dirtyisoyear, dirtyoptions) { var date = todate(dirtydate, dirtyoptions); var isoyear = number(dirtyisoyear); var datestartofyear = startofutcisoweekyear(date, dirtyoptions); var diff = math.floor((date.gettime() - datestartofyear.gettime()) / milliseconds_in_day$3); var fourthofjanuary = new date(0); fourthofjanuary.setutcfullyear(isoyear, 0, 4); fourthofjanuary.setutchours(0, 0, 0, 0); date = startofutcisoweekyear(fourthofjanuary, dirtyoptions); date.setutcdate(date.getutcdate() + diff); return date } var milliseconds_in_minute$6 = 60000; function settimeofday (hours, timeofday) { var isam = timeofday === 0; if (isam) { if (hours === 12) { return 0 } } else { if (hours !== 12) { return 12 + hours } } return hours } var units = { twodigityear: { priority: 10, set: function (datevalues, value) { var century = math.floor(datevalues.date.getutcfullyear() / 100); var year = century * 100 + value; datevalues.date.setutcfullyear(year, 0, 1); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, year: { priority: 10, set: function (datevalues, value) { datevalues.date.setutcfullyear(value, 0, 1); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, isoyear: { priority: 10, set: function (datevalues, value, options) { datevalues.date = startofutcisoweekyear(setutcisoweekyear(datevalues.date, value, options), options); return datevalues } }, quarter: { priority: 20, set: function (datevalues, value) { datevalues.date.setutcmonth((value - 1) * 3, 1); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, month: { priority: 30, set: function (datevalues, value) { datevalues.date.setutcmonth(value, 1); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, isoweek: { priority: 40, set: function (datevalues, value, options) { datevalues.date = startofutcisoweek(setutcisoweek(datevalues.date, value, options), options); return datevalues } }, dayofweek: { priority: 50, set: function (datevalues, value, options) { datevalues.date = setutcday(datevalues.date, value, options); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, dayofisoweek: { priority: 50, set: function (datevalues, value, options) { datevalues.date = setutcisoday(datevalues.date, value, options); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, dayofmonth: { priority: 50, set: function (datevalues, value) { datevalues.date.setutcdate(value); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, dayofyear: { priority: 50, set: function (datevalues, value) { datevalues.date.setutcmonth(0, value); datevalues.date.setutchours(0, 0, 0, 0); return datevalues } }, timeofday: { priority: 60, set: function (datevalues, value, options) { datevalues.timeofday = value; return datevalues } }, hours: { priority: 70, set: function (datevalues, value, options) { datevalues.date.setutchours(value, 0, 0, 0); return datevalues } }, timeofdayhours: { priority: 70, set: function (datevalues, value, options) { var timeofday = datevalues.timeofday; if (timeofday != null) { value = settimeofday(value, timeofday); } datevalues.date.setutchours(value, 0, 0, 0); return datevalues } }, minutes: { priority: 80, set: function (datevalues, value) { datevalues.date.setutcminutes(value, 0, 0); return datevalues } }, seconds: { priority: 90, set: function (datevalues, value) { datevalues.date.setutcseconds(value, 0); return datevalues } }, milliseconds: { priority: 100, set: function (datevalues, value) { datevalues.date.setutcmilliseconds(value); return datevalues } }, timezone: { priority: 110, set: function (datevalues, value) { datevalues.date = new date(datevalues.date.gettime() - value * milliseconds_in_minute$6); return datevalues } }, timestamp: { priority: 120, set: function (datevalues, value) { datevalues.date = new date(value); return datevalues } } }; var timezone_unit_priority = 110; var milliseconds_in_minute$7 = 60000; var longformattingtokensregexp$1 = /(\[[^[]*])|(\\)?(lts|lt|llll|lll|ll|l|llll|lll|ll|l)/g; var defaultparsingtokensregexp = /(\[[^[]*])|(\\)?(x|ss|s|mm|m|hh|h|do|dddd|ddd|dd|d|aa|a|zz|z|yyyy|yy|x|wo|ww|w|sss|ss|s|qo|q|mo|mmmm|mmm|mm|m|hh|h|gggg|gg|e|do|dddo|dddd|ddd|dd|d|a|.)/g; /** * @name parse * @category common helpers * @summary parse the date. * * @description * return the date parsed from string using the given format. * * accepted format tokens: * | unit | priority | token | input examples | * |-------------------------|----------|-------|----------------------------------| * | year | 10 | yy | 00, 01, ..., 99 | * | | | yyyy | 1900, 1901, ..., 2099 | * | iso week-numbering year | 10 | gg | 00, 01, ..., 99 | * | | | gggg | 1900, 1901, ..., 2099 | * | quarter | 20 | q | 1, 2, 3, 4 | * | | | qo | 1st, 2nd, 3rd, 4th | * | month | 30 | m | 1, 2, ..., 12 | * | | | mo | 1st, 2nd, ..., 12th | * | | | mm | 01, 02, ..., 12 | * | | | mmm | jan, feb, ..., dec | * | | | mmmm | january, february, ..., december | * | iso week | 40 | w | 1, 2, ..., 53 | * | | | wo | 1st, 2nd, ..., 53rd | * | | | ww | 01, 02, ..., 53 | * | day of week | 50 | d | 0, 1, ..., 6 | * | | | do | 0th, 1st, ..., 6th | * | | | dd | su, mo, ..., sa | * | | | ddd | sun, mon, ..., sat | * | | | dddd | sunday, monday, ..., saturday | * | day of iso week | 50 | e | 1, 2, ..., 7 | * | day of month | 50 | d | 1, 2, ..., 31 | * | | | do | 1st, 2nd, ..., 31st | * | | | dd | 01, 02, ..., 31 | * | day of year | 50 | ddd | 1, 2, ..., 366 | * | | | dddo | 1st, 2nd, ..., 366th | * | | | dddd | 001, 002, ..., 366 | * | time of day | 60 | a | am, pm | * | | | a | am, pm | * | | | aa | a.m., p.m. | * | hour | 70 | h | 0, 1, ... 23 | * | | | hh | 00, 01, ... 23 | * | time of day hour | 70 | h | 1, 2, ..., 12 | * | | | hh | 01, 02, ..., 12 | * | minute | 80 | m | 0, 1, ..., 59 | * | | | mm | 00, 01, ..., 59 | * | second | 90 | s | 0, 1, ..., 59 | * | | | ss | 00, 01, ..., 59 | * | 1/10 of second | 100 | s | 0, 1, ..., 9 | * | 1/100 of second | 100 | ss | 00, 01, ..., 99 | * | millisecond | 100 | sss | 000, 001, ..., 999 | * | timezone | 110 | z | -01:00, +00:00, ... +12:00 | * | | | zz | -0100, +0000, ..., +1200 | * | seconds timestamp | 120 | x | 512969520 | * | milliseconds timestamp | 120 | x | 512969520900 | * * values will be assigned to the date in the ascending order of its unit's priority. * units of an equal priority overwrite each other in the order of appearance. * * if no values of higher priority are parsed (e.g. when parsing string 'january 1st' without a year), * the values will be taken from 3rd argument `basedate` which works as a context of parsing. * * `basedate` must be passed for correct work of the function. * if you're not sure which `basedate` to supply, create a new instance of date: * `parse('02/11/2014', 'mm/dd/yyyy', new date())` * in this case parsing will be done in the context of the current date. * if `basedate` is `invalid date` or a value not convertible to valid `date`, * then `invalid date` will be returned. * * also, `parse` unfolds long formats like those in [format]{@link https://date-fns.org/docs/format}: * | token | input examples | * |-------|--------------------------------| * | lt | 05:30 a.m. | * | lts | 05:30:15 a.m. | * | l | 07/02/1995 | * | l | 7/2/1995 | * | ll | july 2 1995 | * | ll | jul 2 1995 | * | lll | july 2 1995 05:30 a.m. | * | lll | jul 2 1995 05:30 a.m. | * | llll | sunday, july 2 1995 05:30 a.m. | * | llll | sun, jul 2 1995 05:30 a.m. | * * the characters wrapped in square brackets in the format string are escaped. * * the result may vary by locale. * * if `formatstring` matches with `datestring` but does not provides tokens, `basedate` will be returned. * * if parsing failed, `invalid date` will be returned. * invalid date is a date, whose time value is nan. * time value of date: http://es5.github.io/#x15.9.1.1 * * @param {string} datestring - the string to parse * @param {string} formatstring - the string of tokens * @param {date|string|number} basedate - the date to took the missing higher priority values from * @param {options} [options] - the object with options. see [options]{@link https://date-fns.org/docs/options} * @param {0|1|2} [options.additionaldigits=2] - passed to `todate`. see [todate]{@link https://date-fns.org/docs/todate} * @param {locale} [options.locale=defaultlocale] - the locale object. see [locale]{@link https://date-fns.org/docs/locale} * @param {0|1|2|3|4|5|6} [options.weekstartson=0] - the index of the first day of the week (0 - sunday) * @returns {date} the parsed date * @throws {typeerror} 3 arguments required * @throws {rangeerror} `options.additionaldigits` must be 0, 1 or 2 * @throws {rangeerror} `options.weekstartson` must be between 0 and 6 * @throws {rangeerror} `options.locale` must contain `match` property * @throws {rangeerror} `options.locale` must contain `formatlong` property * * @example * // parse 11 february 2014 from middle-endian format: * var result = parse( * '02/11/2014', * 'mm/dd/yyyy', * new date() * ) * //=> tue feb 11 2014 00:00:00 * * @example * // parse 28th of february in english locale in the context of 2010 year: * import eolocale from 'date-fns/locale/eo' * var result = parse( * '28-a de februaro', * 'do [de] mmmm', * new date(2010, 0, 1) * {locale: eolocale} * ) * //=> sun feb 28 2010 00:00:00 */ function parse (dirtydatestring, dirtyformatstring, dirtybasedate, dirtyoptions) { if (arguments.length < 3) { throw new typeerror('3 arguments required, but only ' + arguments.length + ' present') } var datestring = string(dirtydatestring); var options = dirtyoptions || {}; var weekstartson = options.weekstartson === undefined ? 0 : number(options.weekstartson); // test if weekstartson is between 0 and 6 _and_ is not nan if (!(weekstartson >= 0 && weekstartson <= 6)) { throw new rangeerror('weekstartson must be between 0 and 6 inclusively') } var locale$$1 = options.locale || locale; var localeparsers = locale$$1.parsers || {}; var localeunits = locale$$1.units || {}; if (!locale$$1.match) { throw new rangeerror('locale must contain match property') } if (!locale$$1.formatlong) { throw new rangeerror('locale must contain formatlong property') } var formatstring = string(dirtyformatstring) .replace(longformattingtokensregexp$1, function (substring) { if (substring[0] === '[') { return substring } if (substring[0] === '\\') { return cleanescapedstring$1(substring) } return locale$$1.formatlong(substring) }); if (formatstring === '') { if (datestring === '') { return todate(dirtybasedate, options) } else { return new date(nan) } } var subfnoptions = cloneobject(options); subfnoptions.locale = locale$$1; var tokens = formatstring.match(locale$$1.parsingtokensregexp || defaultparsingtokensregexp); var tokenslength = tokens.length; // if timezone isn't specified, it will be set to the system timezone var setters = [{ priority: timezone_unit_priority, set: datetosystemtimezone, index: 0 }]; var i; for (i = 0; i < tokenslength; i++) { var token = tokens[i]; var parser = localeparsers[token] || parsers[token]; if (parser) { var matchresult; if (parser.match instanceof regexp) { matchresult = parser.match.exec(datestring); } else { matchresult = parser.match(datestring, subfnoptions); } if (!matchresult) { return new date(nan) } var unitname = parser.unit; var unit = localeunits[unitname] || units[unitname]; setters.push({ priority: unit.priority, set: unit.set, value: parser.parse(matchresult, subfnoptions), index: setters.length }); var substring = matchresult[0]; datestring = datestring.slice(substring.length); } else { var head = tokens[i].match(/^\[.*]$/) ? tokens[i].replace(/^\[|]$/g, '') : tokens[i]; if (datestring.indexof(head) === 0) { datestring = datestring.slice(head.length); } else { return new date(nan) } } } var uniqueprioritysetters = setters .map(function (setter) { return setter.priority }) .sort(function (a, b) { return a - b }) .filter(function (priority, index, array) { return array.indexof(priority) === index }) .map(function (priority) { return setters .filter(function (setter) { return setter.priority === priority }) .reverse() }) .map(function (setterarray) { return setterarray[0] }); var date = todate(dirtybasedate, options); if (isnan(date)) { return new date(nan) } // convert the date in system timezone to the same date in utc+00:00 timezone. // this ensures that when utc functions will be implemented, locales will be compatible with them. // see an issue about utc functions: https://github.com/date-fns/date-fns/issues/37 var utcdate = subminutes(date, date.gettimezoneoffset()); var datevalues = {date: utcdate}; var setterslength = uniqueprioritysetters.length; for (i = 0; i < setterslength; i++) { var setter = uniqueprioritysetters[i]; datevalues = setter.set(datevalues, setter.value, subfnoptions); } return datevalues.date } function datetosystemtimezone (datevalues) { var date = datevalues.date; var time = date.gettime(); // get the system timezone offset at (moment of time - offset) var offset = date.gettimezoneoffset(); // get the system timezone offset at the exact moment of time offset = new date(time + offset * milliseconds_in_minute$7).gettimezoneoffset(); // convert date in timezone "utc+00:00" to the system timezone datevalues.date = new date(time + offset * milliseconds_in_minute$7); return datevalues } function cleanescapedstring$1 (input) { if (input.match(/\[[\s\s]/)) { return input.replace(/^\[|]$/g, '') } return input.replace(/\\/g, '') } // this file is generated automatically by `scripts/build/indices.js`. please, don't change it. // /** * custom parse behavior on top of date-fns parse function. */ function parsedate$1 (date, format$$1) { if (typeof date !== 'string') { return isvalid(date) ? date : null; } var parsed = parse(date, format$$1, new date()); // if date is not valid or the formatted output after parsing does not match // the string value passed in (avoids overflows) if (!isvalid(parsed) || format(parsed, format$$1) !== date) { return null; } return parsed; } var aftervalidator = function (value, ref) { if ( ref === void 0 ) ref = {}; var targetvalue = ref.targetvalue; var inclusion = ref.inclusion; if ( inclusion === void 0 ) inclusion = false; var format$$1 = ref.format; if (typeof format$$1 === 'undefined') { format$$1 = inclusion; inclusion = false; } value = parsedate$1(value, format$$1); targetvalue = parsedate$1(targetvalue, format$$1); // if either is not valid. if (!value || !targetvalue) { return false; } return isafter(value, targetvalue) || (inclusion && isequal(value, targetvalue)); }; var options = { hastarget: true, isdate: true }; // required to convert from a list of array values to an object. var paramnames = ['targetvalue', 'inclusion', 'format']; var after = { validate: aftervalidator, options: options, paramnames: paramnames }; /** * some alpha regex helpers. * https://github.com/chriso/validator.js/blob/master/src/lib/alpha.js */ var alpha = { en: /^[a-z]*$/i, cs: /^[a-záčďéěíňóřšťúůýž]*$/i, da: /^[a-zæøå]*$/i, de: /^[a-zäöüß]*$/i, es: /^[a-záéíñóúü]*$/i, fr: /^[a-zàâæçéèêëïîôœùûüÿ]*$/i, lt: /^[a-ząčęėįšųūž]*$/i, nl: /^[a-zéëïóöü]*$/i, hu: /^[a-záéíóöőúüű]*$/i, pl: /^[a-ząćęśłńóżź]*$/i, pt: /^[a-zãáàâçéêíõóôúü]*$/i, ru: /^[а-яё]*$/i, sk: /^[a-záäčďéíĺľňóŕšťúýž]*$/i, sr: /^[a-zčćžšđ]*$/i, tr: /^[a-zçğiıöşü]*$/i, uk: /^[а-щьюяєіїґ]*$/i, ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]*$/ }; var alphaspaces = { en: /^[a-z\s]*$/i, cs: /^[a-záčďéěíňóřšťúůýž\s]*$/i, da: /^[a-zæøå\s]*$/i, de: /^[a-zäöüß\s]*$/i, es: /^[a-záéíñóúü\s]*$/i, fr: /^[a-zàâæçéèêëïîôœùûüÿ\s]*$/i, lt: /^[a-ząčęėįšųūž\s]*$/i, nl: /^[a-zéëïóöü\s]*$/i, hu: /^[a-záéíóöőúüű\s]*$/i, pl: /^[a-ząćęśłńóżź\s]*$/i, pt: /^[a-zãáàâçéêíõóôúü\s]*$/i, ru: /^[а-яё\s]*$/i, sk: /^[a-záäčďéíĺľňóŕšťúýž\s]*$/i, sr: /^[a-zčćžšđ\s]*$/i, tr: /^[a-zçğiıöşü\s]*$/i, uk: /^[а-щьюяєіїґ\s]*$/i, ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ\s]*$/ }; var alphanumeric = { en: /^[0-9a-z]*$/i, cs: /^[0-9a-záčďéěíňóřšťúůýž]*$/i, da: /^[0-9a-zæøå]$/i, de: /^[0-9a-zäöüß]*$/i, es: /^[0-9a-záéíñóúü]*$/i, fr: /^[0-9a-zàâæçéèêëïîôœùûüÿ]*$/i, lt: /^[0-9a-ząčęėįšųūž]*$/i, hu: /^[0-9a-záéíóöőúüű]*$/i, nl: /^[0-9a-zéëïóöü]*$/i, pl: /^[0-9a-ząćęśłńóżź]*$/i, pt: /^[0-9a-zãáàâçéêíõóôúü]*$/i, ru: /^[0-9а-яё]*$/i, sk: /^[0-9a-záäčďéíĺľňóŕšťúýž]*$/i, sr: /^[0-9a-zčćžšđ]*$/i, tr: /^[0-9a-zçğiıöşü]*$/i, uk: /^[0-9а-щьюяєіїґ]*$/i, ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]*$/ }; var alphadash = { en: /^[0-9a-z_-]*$/i, cs: /^[0-9a-záčďéěíňóřšťúůýž_-]*$/i, da: /^[0-9a-zæøå_-]*$/i, de: /^[0-9a-zäöüß_-]*$/i, es: /^[0-9a-záéíñóúü_-]*$/i, fr: /^[0-9a-zàâæçéèêëïîôœùûüÿ_-]*$/i, lt: /^[0-9a-ząčęėįšųūž_-]*$/i, nl: /^[0-9a-zéëïóöü_-]*$/i, hu: /^[0-9a-záéíóöőúüű_-]*$/i, pl: /^[0-9a-ząćęśłńóżź_-]*$/i, pt: /^[0-9a-zãáàâçéêíõóôúü_-]*$/i, ru: /^[0-9а-яё_-]*$/i, sk: /^[0-9a-záäčďéíĺľňóŕšťúýž_-]*$/i, sr: /^[0-9a-zčćžšđ_-]*$/i, tr: /^[0-9a-zçğiıöşü_-]*$/i, uk: /^[0-9а-щьюяєіїґ_-]*$/i, ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ_-]*$/ }; var validate = function (value, ref) { if ( ref === void 0 ) ref = {}; var locale = ref.locale; if (array.isarray(value)) { return value.every(function (val) { return validate(val, [locale]); }); } // match at least one locale. if (! locale) { return object.keys(alpha).some(function (loc) { return alpha[loc].test(value); }); } return (alpha[locale] || alpha.en).test(value); }; var paramnames$1 = ['locale']; var alpha$1 = { validate: validate, paramnames: paramnames$1 }; var validate$1 = function (value, ref) { if ( ref === void 0 ) ref = {}; var locale = ref.locale; if (array.isarray(value)) { return value.every(function (val) { return validate$1(val, [locale]); }); } // match at least one locale. if (! locale) { return object.keys(alphadash).some(function (loc) { return alphadash[loc].test(value); }); } return (alphadash[locale] || alphadash.en).test(value); }; var paramnames$2 = ['locale']; var alpha_dash = { validate: validate$1, paramnames: paramnames$2 }; var validate$2 = function (value, ref) { if ( ref === void 0 ) ref = {}; var locale = ref.locale; if (array.isarray(value)) { return value.every(function (val) { return validate$2(val, [locale]); }); } // match at least one locale. if (! locale) { return object.keys(alphanumeric).some(function (loc) { return alphanumeric[loc].test(value); }); } return (alphanumeric[locale] || alphanumeric.en).test(value); }; var paramnames$3 = ['locale']; var alpha_num = { validate: validate$2, paramnames: paramnames$3 }; var validate$3 = function (value, ref) { if ( ref === void 0 ) ref = {}; var locale = ref.locale; if (array.isarray(value)) { return value.every(function (val) { return validate$3(val, [locale]); }); } // match at least one locale. if (! locale) { return object.keys(alphaspaces).some(function (loc) { return alphaspaces[loc].test(value); }); } return (alphaspaces[locale] || alphaspaces.en).test(value); }; var paramnames$4 = ['locale']; var alpha_spaces = { validate: validate$3, paramnames: paramnames$4 }; var validate$4 = function (value, ref) { if ( ref === void 0 ) ref = {}; var targetvalue = ref.targetvalue; var inclusion = ref.inclusion; if ( inclusion === void 0 ) inclusion = false; var format$$1 = ref.format; if (typeof format$$1 === 'undefined') { format$$1 = inclusion; inclusion = false; } value = parsedate$1(value, format$$1); targetvalue = parsedate$1(targetvalue, format$$1); // if either is not valid. if (!value || !targetvalue) { return false; } return isbefore(value, targetvalue) || (inclusion && isequal(value, targetvalue)); }; var options$1 = { hastarget: true, isdate: true }; var paramnames$5 = ['targetvalue', 'inclusion', 'format']; var before = { validate: validate$4, options: options$1, paramnames: paramnames$5 }; var validate$5 = function (value, ref) { if ( ref === void 0 ) ref = {}; var min = ref.min; var max = ref.max; if (array.isarray(value)) { return value.every(function (val) { return validate$5(val, { min: min, max: max }); }); } return number(min) <= value && number(max) >= value; }; var paramnames$6 = ['min', 'max']; var between = { validate: validate$5, paramnames: paramnames$6 }; var validate$6 = function (value, ref) { var targetvalue = ref.targetvalue; return string(value) === string(targetvalue); }; var options$2 = { hastarget: true }; var paramnames$7 = ['targetvalue']; var confirmed = { validate: validate$6, options: options$2, paramnames: paramnames$7 }; function unwrapexports (x) { return x && x.__esmodule && object.prototype.hasownproperty.call(x, 'default') ? x['default'] : x; } function createcommonjsmodule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var assertstring_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = assertstring; function assertstring(input) { var isstring = typeof input === 'string' || input instanceof string; if (!isstring) { throw new typeerror('this library (validator.js) validates strings only'); } } module.exports = exports['default']; }); unwrapexports(assertstring_1); var iscreditcard_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = iscreditcard; var _assertstring2 = _interoprequiredefault(assertstring_1); function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; } /* eslint-disable max-len */ 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}|6[27][0-9]{14})$/; /* eslint-enable max-len */ function iscreditcard(str) { (0, _assertstring2.default)(str); var sanitized = str.replace(/[- ]+/g, ''); if (!creditcard.test(sanitized)) { return false; } var sum = 0; var digit = void 0; var tmpnum = void 0; var shoulddouble = void 0; for (var i = sanitized.length - 1; i >= 0; i--) { digit = sanitized.substring(i, i + 1); tmpnum = parseint(digit, 10); if (shoulddouble) { tmpnum *= 2; if (tmpnum >= 10) { sum += tmpnum % 10 + 1; } else { sum += tmpnum; } } else { sum += tmpnum; } shoulddouble = !shoulddouble; } return !!(sum % 10 === 0 ? sanitized : false); } module.exports = exports['default']; }); var iscreditcard = unwrapexports(iscreditcard_1); var validate$7 = function (value) { return iscreditcard(string(value)); }; var credit_card = { validate: validate$7 }; var validate$8 = function (value, ref) { if ( ref === void 0 ) ref = {}; var min$$1 = ref.min; var max$$1 = ref.max; var inclusivity = ref.inclusivity; if ( inclusivity === void 0 ) inclusivity = '()'; var format$$1 = ref.format; if (typeof format$$1 === 'undefined') { format$$1 = inclusivity; inclusivity = '()'; } var mindate = parsedate$1(string(min$$1), format$$1); var maxdate = parsedate$1(string(max$$1), format$$1); var dateval = parsedate$1(string(value), format$$1); if (!mindate || !maxdate || !dateval) { return false; } if (inclusivity === '()') { return isafter(dateval, mindate) && isbefore(dateval, maxdate); } if (inclusivity === '(]') { return isafter(dateval, mindate) && (isequal(dateval, maxdate) || isbefore(dateval, maxdate)); } if (inclusivity === '[)') { return isbefore(dateval, maxdate) && (isequal(dateval, mindate) || isafter(dateval, mindate)); } return isequal(dateval, maxdate) || isequal(dateval, mindate) || (isbefore(dateval, maxdate) && isafter(dateval, mindate)); }; var options$3 = { isdate: true }; var paramnames$8 = ['min', 'max', 'inclusivity', 'format']; var date_between = { validate: validate$8, options: options$3, paramnames: paramnames$8 }; var validate$9 = function (value, ref) { var format = ref.format; return !!parsedate$1(value, format); }; var options$4 = { isdate: true }; var paramnames$9 = ['format']; var date_format = { validate: validate$9, options: options$4, paramnames: paramnames$9 }; var validate$a = function (value, ref) { if ( ref === void 0 ) ref = {}; var decimals = ref.decimals; if ( decimals === void 0 ) decimals = '*'; var separator = ref.separator; if ( separator === void 0 ) separator = '.'; if (array.isarray(value)) { return value.every(function (val) { return validate$a(val, { decimals: decimals, separator: separator }); }); } if (value === null || value === undefined || value === '') { return true; } // if is 0. if (number(decimals) === 0) { return /^-?\d*$/.test(value); } var regexpart = decimals === '*' ? '+' : ("{1," + decimals + "}"); var regex = new regexp(("^-?\\d*(\\" + separator + "\\d" + regexpart + ")?$")); if (! regex.test(value)) { return false; } var parsedvalue = parsefloat(value); // eslint-disable-next-line return parsedvalue === parsedvalue; }; var paramnames$a = ['decimals', 'separator']; var decimal = { validate: validate$a, paramnames: paramnames$a }; var validate$b = function (value, ref) { var length = ref[0]; if (array.isarray(value)) { return value.every(function (val) { return validate$b(val, [length]); }); } var strval = string(value); return /^[0-9]*$/.test(strval) && strval.length === number(length); }; var digits = { validate: validate$b }; var validateimage = function (file, width, height) { var url = window.url || window.webkiturl; return new promise(function (resolve) { var image = new image(); image.onerror = function () { return resolve({ valid: false }); }; image.onload = function () { return resolve({ valid: image.width === number(width) && image.height === number(height) }); }; image.src = url.createobjecturl(file); }); }; var validate$c = function (files, ref) { var width = ref[0]; var height = ref[1]; var list = []; for (var i = 0; i < files.length; i++) { // if file is not an image, reject. if (! /\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(files[i].name)) { return false; } list.push(files[i]); } return promise.all(list.map(function (file) { return validateimage(file, width, height); })); }; var dimensions = { validate: validate$c }; var merge_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = merge; function merge() { var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaults = arguments[1]; for (var key in defaults) { if (typeof obj[key] === 'undefined') { obj[key] = defaults[key]; } } return obj; } module.exports = exports['default']; }); unwrapexports(merge_1); var isbytelength_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); 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; }; exports.default = isbytelength; var _assertstring2 = _interoprequiredefault(assertstring_1); function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; } /* eslint-disable prefer-rest-params */ function isbytelength(str, options) { (0, _assertstring2.default)(str); var min = void 0; var max = void 0; if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') { min = options.min || 0; max = options.max; } else { // backwards compatibility: isbytelength(str, min [, max]) min = arguments[1]; max = arguments[2]; } var len = encodeuri(str).split(/%..|./).length - 1; return len >= min && (typeof max === 'undefined' || len <= max); } module.exports = exports['default']; }); unwrapexports(isbytelength_1); var isfqdn_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = isfqdn; var _assertstring2 = _interoprequiredefault(assertstring_1); var _merge2 = _interoprequiredefault(merge_1); function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; } var default_fqdn_options = { require_tld: true, allow_underscores: false, allow_trailing_dot: false }; function isfqdn(str, options) { (0, _assertstring2.default)(str); options = (0, _merge2.default)(options, default_fqdn_options); /* remove the optional trailing dot before checking validity */ if (options.allow_trailing_dot && str[str.length - 1] === '.') { str = str.substring(0, str.length - 1); } var parts = str.split('.'); for (var i = 0; i < parts.length; i++) { if (parts[i].length > 63) { return false; } } if (options.require_tld) { var tld = parts.pop(); if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { return false; } // disallow spaces if (/[\s\u2002-\u200b\u202f\u205f\u3000\ufeff\udb40\udc20]/.test(tld)) { return false; } } for (var part, _i = 0; _i < parts.length; _i++) { part = parts[_i]; if (options.allow_underscores) { part = part.replace(/_/g, ''); } if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) { return false; } // disallow full-width chars if (/[\uff01-\uff5e]/.test(part)) { return false; } if (part[0] === '-' || part[part.length - 1] === '-') { return false; } } return true; } module.exports = exports['default']; }); unwrapexports(isfqdn_1); var isip_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = isip; var _assertstring2 = _interoprequiredefault(assertstring_1); function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; } var ipv4maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; var ipv6block = /^[0-9a-f]{1,4}$/i; function isip(str) { var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; (0, _assertstring2.default)(str); version = string(version); if (!version) { return isip(str, 4) || isip(str, 6); } else if (version === '4') { if (!ipv4maybe.test(str)) { return false; } var parts = str.split('.').sort(function (a, b) { return a - b; }); return parts[3] <= 255; } else if (version === '6') { var blocks = str.split(':'); var foundomissionblock = false; // marker to indicate :: // at least some os accept the last 32 bits of an ipv6 address // (i.e. 2 of the blocks) in ipv4 notation, and rfc 3493 says // that '::ffff:a.b.c.d' is valid for ipv4-mapped ipv6 addresses, // and '::a.b.c.d' is deprecated, but also valid. var foundipv4transitionblock = isip(blocks[blocks.length - 1], 4); var expectednumberofblocks = foundipv4transitionblock ? 7 : 8; if (blocks.length > expectednumberofblocks) { return false; } // initial or final :: if (str === '::') { return true; } else if (str.substr(0, 2) === '::') { blocks.shift(); blocks.shift(); foundomissionblock = true; } else if (str.substr(str.length - 2) === '::') { blocks.pop(); blocks.pop(); foundomissionblock = true; } for (var i = 0; i < blocks.length; ++i) { // test for a :: which can not be at the string start/end // since those cases have been handled above if (blocks[i] === '' && i > 0 && i < blocks.length - 1) { if (foundomissionblock) { return false; // multiple :: in address } foundomissionblock = true; } else if (foundipv4transitionblock && i === blocks.length - 1) ; else if (!ipv6block.test(blocks[i])) { return false; } } if (foundomissionblock) { return blocks.length >= 1; } return blocks.length === expectednumberofblocks; } return false; } module.exports = exports['default']; }); var isip = unwrapexports(isip_1); var isemail_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = isemail; var _assertstring2 = _interoprequiredefault(assertstring_1); var _merge2 = _interoprequiredefault(merge_1); var _isbytelength2 = _interoprequiredefault(isbytelength_1); var _isfqdn2 = _interoprequiredefault(isfqdn_1); var _isip2 = _interoprequiredefault(isip_1); function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; } var default_email_options = { allow_display_name: false, require_display_name: false, allow_utf8_local_part: true, require_tld: true }; /* eslint-disable max-len */ /* eslint-disable no-control-regex */ var displayname = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\,\.\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef\s]*<(.+)>$/i; var emailuserpart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i; var gmailuserpart = /^[a-z\d]+$/; var quotedemailuser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i; var emailuserutf8part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00a0-\ud7ff\uf900-\ufdcf\ufdf0-\uffef]+$/i; 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; /* eslint-enable max-len */ /* eslint-enable no-control-regex */ function isemail(str, options) { (0, _assertstring2.default)(str); options = (0, _merge2.default)(options, default_email_options); if (options.require_display_name || options.allow_display_name) { var display_email = str.match(displayname); if (display_email) { str = display_email[1]; } else if (options.require_display_name) { return false; } } var parts = str.split('@'); var domain = parts.pop(); var user = parts.join('@'); var lower_domain = domain.tolowercase(); if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) { /* previously we removed dots for gmail addresses before validating. this was removed because it allows `multiple..dots@gmail.com` to be reported as valid, but it is not. gmail only normalizes single dots, removing them from here is pointless, should be done in normalizeemail */ user = user.tolowercase(); // removing sub-address from username before gmail validation var username = user.split('+')[0]; // dots are not included in gmail length restriction if (!(0, _isbytelength2.default)(username.replace('.', ''), { min: 6, max: 30 })) { return false; } var _user_parts = username.split('.'); for (var i = 0; i < _user_parts.length; i++) { if (!gmailuserpart.test(_user_parts[i])) { return false; } } } if (!(0, _isbytelength2.default)(user, { max: 64 }) || !(0, _isbytelength2.default)(domain, { max: 254 })) { return false; } if (!(0, _isfqdn2.default)(domain, { require_tld: options.require_tld })) { if (!options.allow_ip_domain) { return false; } if (!(0, _isip2.default)(domain)) { if (!domain.startswith('[') || !domain.endswith(']')) { return false; } var nobracketdomain = domain.substr(1, domain.length - 2); if (nobracketdomain.length === 0 || !(0, _isip2.default)(nobracketdomain)) { return false; } } } if (user[0] === '"') { user = user.slice(1, user.length - 1); return options.allow_utf8_local_part ? quotedemailuserutf8.test(user) : quotedemailuser.test(user); } var pattern = options.allow_utf8_local_part ? emailuserutf8part : emailuserpart; var user_parts = user.split('.'); for (var _i = 0; _i < user_parts.length; _i++) { if (!pattern.test(user_parts[_i])) { return false; } } return true; } module.exports = exports['default']; }); var isemail = unwrapexports(isemail_1); var validate$d = function (value, options) { if ( options === void 0 ) options = {}; if (options.multiple) { value = value.split(',').map(function (emailstr) { return emailstr.trim(); }); } if (array.isarray(value)) { return value.every(function (val) { return isemail(string(val), options); }); } return isemail(string(value), options); }; var email = { validate: validate$d }; // var supportspassive = true; var detectpassivesupport = function () { try { var opts = object.defineproperty({}, 'passive', { get: function get () { supportspassive = true; } }); window.addeventlistener('testpassive', null, opts); window.removeeventlistener('testpassive', null, opts); } catch (e) { supportspassive = false; } return supportspassive; }; var addeventlistener = function (el, eventname, cb) { el.addeventlistener(eventname, cb, supportspassive ? { passive: true } : false); }; var istextinput = function (el) { return includes(['text', 'password', 'search', 'email', 'tel', 'url', 'textarea'], el.type); }; var ischeckboxorradioinput = function (el) { return includes(['radio', 'checkbox'], el.type); }; var isdateinput = function (el) { return includes(['date', 'week', 'month', 'datetime-local', 'time'], el.type); }; /** * gets the data attribute. the name must be kebab-case. */ var getdataattribute = function (el, name) { return el.getattribute(("data-vv-" + name)); }; /** * checks if the values are either null or undefined. */ var isnullorundefined = function () { var values = [], len = arguments.length; while ( len-- ) values[ len ] = arguments[ len ]; return values.every(function (value) { return value === null || value === undefined; }); }; /** * creates the default flags object. */ var createflags = function () { return ({ untouched: true, touched: false, dirty: false, pristine: true, valid: null, invalid: null, validated: false, pending: false, required: false, changed: false }); }; /** * shallow object comparison. */ var isequal$1 = function (lhs, rhs) { if (lhs instanceof regexp && rhs instanceof regexp) { return isequal$1(lhs.source, rhs.source) && isequal$1(lhs.flags, rhs.flags); } if (array.isarray(lhs) && array.isarray(rhs)) { if (lhs.length !== rhs.length) { return false; } for (var i = 0; i < lhs.length; i++) { if (!isequal$1(lhs[i], rhs[i])) { return false; } } return true; } // if both are objects, compare each key recursively. if (isobject(lhs) && isobject(rhs)) { return object.keys(lhs).every(function (key) { return isequal$1(lhs[key], rhs[key]); }) && object.keys(rhs).every(function (key) { return isequal$1(lhs[key], rhs[key]); }); } return lhs === rhs; }; /** * determines the input field scope. */ var getscope = function (el) { var scope = getdataattribute(el, 'scope'); if (isnullorundefined(scope)) { var form = getform(el); if (form) { scope = getdataattribute(form, 'scope'); } } return !isnullorundefined(scope) ? scope : null; }; /** * get the closest form element. */ var getform = function (el) { if (isnullorundefined(el)) { return null; } if (el.tagname === 'form') { return el; } if (!isnullorundefined(el.form)) { return el.form; } return !isnullorundefined(el.parentnode) ? getform(el.parentnode) : null; }; /** * gets the value in an object safely. */ var getpath = function (path, target, def) { if ( def === void 0 ) def = undefined; if (!path || !target) { return def; } var value = target; path.split('.').every(function (prop) { if (prop in value) { value = value[prop]; return true; } value = def; return false; }); return value; }; /** * checks if path exists within an object. */ var haspath = function (path, target) { var obj = target; return path.split('.').every(function (prop) { if (prop in obj) { obj = obj[prop]; return true; } return false; }); }; /** * parses a rule string expression. */ var parserule = function (rule) { var params = []; var name = rule.split(':')[0]; if (includes(rule, ':')) { params = rule.split(':').slice(1).join(':').split(','); } return { name: name, params: params }; }; /** * debounces a function. */ var debounce = function (fn, wait, immediate, token) { if ( wait === void 0 ) wait = 0; if ( immediate === void 0 ) immediate = false; if ( token === void 0 ) token = { cancelled: false }; if (wait === 0) { return fn; } var timeout; return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var later = function () { timeout = null; if (!immediate && !token.cancelled) { fn.apply(void 0, args); } }; /* istanbul ignore next */ var callnow = immediate && !timeout; cleartimeout(timeout); timeout = settimeout(later, wait); /* istanbul ignore next */ if (callnow) { fn.apply(void 0, args); } }; }; /** * appends a rule definition to a list of rules. */ var appendrule = function (rule, rules) { if (!rules) { return normalizerules(rule); } if (!rule) { return normalizerules(rules); } if (typeof rules === 'string') { rules = normalizerules(rules); } return assign({}, rules, normalizerules(rule)); }; /** * normalizes the given rules expression. */ var normalizerules = function (rules) { // if falsy value return an empty object. if (!rules) { return {}; } if (isobject(rules)) { // $flowfixme return object.keys(rules).reduce(function (prev, curr) { var params = []; // $flowfixme if (rules[curr] === true) { params = []; } else if (array.isarray(rules[curr])) { params = rules[curr]; } else if (isobject(rules[curr])) { params = rules[curr]; } else { params = [rules[curr]]; } // $flowfixme if (rules[curr] !== false) { prev[curr] = params; } return prev; }, {}); } if (typeof rules !== 'string') { warn('rules must be either a string or an object.'); return {}; } return rules.split('|').reduce(function (prev, rule) { var parsedrule = parserule(rule); if (!parsedrule.name) { return prev; } prev[parsedrule.name] = parsedrule.params; return prev; }, {}); }; /** * emits a warning to the console. */ var warn = function (message) { console.warn(("[vee-validate] " + message)); // eslint-disable-line }; /** * creates a branded error object. */ var createerror = function (message) { return new error(("[vee-validate] " + message)); }; /** * checks if the value is an object. */ var isobject = function (obj) { return obj !== null && obj && typeof obj === 'object' && ! array.isarray(obj); }; /** * checks if a function is callable. */ var iscallable = function (func) { return typeof func === 'function'; }; /** * check if element has the css class on it. */ var hasclass = function (el, classname) { if (el.classlist) { return el.classlist.contains(classname); } return !!el.classname.match(new regexp(("(\\s|^)" + classname + "(\\s|$)"))); }; /** * adds the provided css classname to the element. */ var addclass = function (el, classname) { if (el.classlist) { el.classlist.add(classname); return; } if (!hasclass(el, classname)) { el.classname += " " + classname; } }; /** * remove the provided css classname from the element. */ var removeclass = function (el, classname) { if (el.classlist) { el.classlist.remove(classname); return; } if (hasclass(el, classname)) { var reg = new regexp(("(\\s|^)" + classname + "(\\s|$)")); el.classname = el.classname.replace(reg, ' '); } }; /** * adds or removes a class name on the input depending on the status flag. */ var toggleclass = function (el, classname, status) { if (!el || !classname) { return; } if (array.isarray(classname)) { classname.foreach(function (item) { return toggleclass(el, item, status); }); return; } if (status) { return addclass(el, classname); } removeclass(el, classname); }; /** * converts an array-like object to array, provides a simple polyfill for array.from */ var toarray = function (arraylike) { if (iscallable(array.from)) { return array.from(arraylike); } var array = []; var length = arraylike.length; /* istanbul ignore next */ for (var i = 0; i < length; i++) { array.push(arraylike[i]); } /* istanbul ignore next */ return array; }; /** * assign polyfill from the mdn. */ var assign = function (target) { var others = [], len = arguments.length - 1; while ( len-- > 0 ) others[ len ] = arguments[ len + 1 ]; /* istanbul ignore else */ if (iscallable(object.assign)) { return object.assign.apply(object, [ target ].concat( others )); } /* istanbul ignore next */ if (target == null) { throw new typeerror('cannot convert undefined or null to object'); } /* istanbul ignore next */ var to = object(target); /* istanbul ignore next */ others.foreach(function (arg) { // skip over if undefined or null if (arg != null) { object.keys(arg).foreach(function (key) { to[key] = arg[key]; }); } }); /* istanbul ignore next */ return to; }; var id = 0; var idtemplate = '{id}'; /** * generates a unique id. */ var uniqid = function () { // handle too many uses of uniqid, although unlikely. if (id >= 9999) { id = 0; // shift the template. idtemplate = idtemplate.replace('{id}', '_{id}'); } id++; var newid = idtemplate.replace('{id}', string(id)); return newid; }; /** * finds the first element that satisfies the predicate callback, polyfills array.find */ var find = function (arraylike, predicate) { var array = array.isarray(arraylike) ? arraylike : toarray(arraylike); for (var i = 0; i < array.length; i++) { if (predicate(array[i])) { return array[i]; } } return undefined; }; var isbuiltincomponent = function (vnode) { if (!vnode) { return false; } var tag = vnode.componentoptions.tag; return /^(keep-alive|transition|transition-group)$/.test(tag); }; var makeeventsarray = function (events) { return (typeof events === 'string' && events.length) ? events.split('|') : []; }; var makedelayobject = function (events, delay, delayconfig) { if (typeof delay === 'number') { return events.reduce(function (prev, e) { prev[e] = delay; return prev; }, {}); } return events.reduce(function (prev, e) { if (typeof delay === 'object' && e in delay) { prev[e] = delay[e]; return prev; } if (typeof delayconfig === 'number') { prev[e] = delayconfig; return prev; } prev[e] = (delayconfig && delayconfig[e]) || 0; return prev; }, {}); }; var deepparseint = function (input) { if (typeof input === 'number') { return input; } if (typeof input === 'string') { return parseint(input); } var map = {}; for (var element in input) { map[element] = parseint(input[element]); } return map; }; var merge$1 = function (target, source) { if (! (isobject(target) && isobject(source))) { return target; } object.keys(source).foreach(function (key) { var obj, obj$1; if (isobject(source[key])) { if (! target[key]) { assign(target, ( obj = {}, obj[key] = {}, obj )); } merge$1(target[key], source[key]); return; } assign(target, ( obj$1 = {}, obj$1[key] = source[key], obj$1 )); }); return target; }; var fillrulesfromelement = function (el, rules) { if (el.required) { rules = appendrule('required', rules); } if (istextinput(el)) { if (el.type === 'email') { rules = appendrule(("email" + (el.multiple ? ':multiple' : '')), rules); } if (el.pattern) { rules = appendrule({ regex: el.pattern }, rules); } // 524288 is the max on some browsers and test environments. if (el.maxlength >= 0 && el.maxlength < 524288) { rules = appendrule(("max:" + (el.maxlength)), rules); } if (el.minlength > 0) { rules = appendrule(("min:" + (el.minlength)), rules); } return rules; } if (el.type === 'number') { rules = appendrule('decimal', rules); if (el.min !== '') { rules = appendrule(("min_value:" + (el.min)), rules); } if (el.max !== '') { rules = appendrule(("max_value:" + (el.max)), rules); } return rules; } if (isdateinput(el)) { var timeformat = el.step && number(el.step) < 60 ? 'hh:mm:ss' : 'hh:mm'; if (el.type === 'date') { return appendrule('date_format:yyyy-mm-dd', rules); } if (el.type === 'datetime-local') { return appendrule(("date_format:yyyy-mm-ddt" + timeformat), rules); } if (el.type === 'month') { return appendrule('date_format:yyyy-mm', rules); } if (el.type === 'week') { return appendrule('date_format:yyyy-[w]ww', rules); } if (el.type === 'time') { return appendrule(("date_format:" + timeformat), rules); } } return rules; }; var values = function (obj) { if (iscallable(object.values)) { return object.values(obj); } // fallback to keys() /* istanbul ignore next */ return obj[object.keys(obj)[0]]; }; var parseselector = function (selector) { var rule = null; if (includes(selector, ':')) { rule = selector.split(':').pop(); selector = selector.replace((":" + rule), ''); } if (selector[0] === '#') { return { id: selector.slice(1), rule: rule, name: null, scope: null }; } var scope = null; var name = selector; if (includes(selector, '.')) { var parts = selector.split('.'); scope = parts[0]; name = parts.slice(1).join('.'); } return { id: null, scope: scope, name: name, rule: rule }; }; var includes = function (collection, item) { return collection.indexof(item) !== -1; }; var validate$e = function (value, options) { if (array.isarray(value)) { return value.every(function (val) { return validate$e(val, options); }); } return toarray(options).some(function (item) { // eslint-disable-next-line return item == value; }); }; var included = { validate: validate$e }; var validate$f = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return !validate$e.apply(void 0, args); }; var excluded = { validate: validate$f }; var validate$g = function (files, extensions) { var regex = new regexp((".(" + (extensions.join('|')) + ")$"), 'i'); return files.every(function (file) { return regex.test(file.name); }); }; var ext = { validate: validate$g }; var validate$h = function (files) { return files.every(function (file) { return /\.(jpg|svg|jpeg|png|bmp|gif)$/i.test(file.name); }); }; var image = { validate: validate$h }; var validate$i = function (value) { if (array.isarray(value)) { return value.every(function (val) { return /^-?[0-9]+$/.test(string(val)); }); } return /^-?[0-9]+$/.test(string(value)); }; var integer = { validate: validate$i }; var validate$j = function (value, ref) { if ( ref === void 0 ) ref = {}; var version = ref.version; if ( version === void 0 ) version = 4; if (isnullorundefined(value)) { value = ''; } if (array.isarray(value)) { return value.every(function (val) { return isip(val, version); }); } return isip(value, version); }; var paramnames$b = ['version']; var ip = { validate: validate$j, paramnames: paramnames$b }; var validate$k = function (value, ref) { if ( ref === void 0 ) ref = []; var other = ref[0]; return value === other; }; var is = { validate: validate$k }; var validate$l = function (value, ref) { if ( ref === void 0 ) ref = []; var other = ref[0]; return value !== other; }; var is_not = { validate: validate$l }; /** * @param {array|string} value * @param {number} length * @param {number} max */ var compare = function (value, length, max) { if (max === undefined) { return value.length === length; } // cast to number. max = number(max); return value.length >= length && value.length <= max; }; var validate$m = function (value, ref) { var length = ref[0]; var max = ref[1]; if ( max === void 0 ) max = undefined; length = number(length); if (value === undefined || value === null) { return false; } if (typeof value === 'number') { value = string(value); } if (!value.length) { value = toarray(value); } return compare(value, length, max); }; var length = { validate: validate$m }; var validate$n = function (value, ref) { var length = ref[0]; if (value === undefined || value === null) { return length >= 0; } if (array.isarray(value)) { return value.every(function (val) { return validate$n(val, [length]); }); } return string(value).length <= length; }; var max$1 = { validate: validate$n }; var validate$o = function (value, ref) { var max = ref[0]; if (value === null || value === undefined || value === '') { return false; } if (array.isarray(value)) { return value.length > 0 && value.every(function (val) { return validate$o(val, [max]); }); } return number(value) <= max; }; var max_value = { validate: validate$o }; var validate$p = function (files, mimes) { var regex = new regexp(((mimes.join('|').replace('*', '.+')) + "$"), 'i'); return files.every(function (file) { return regex.test(file.type); }); }; var mimes = { validate: validate$p }; var validate$q = function (value, ref) { var length = ref[0]; if (value === undefined || value === null) { return false; } if (array.isarray(value)) { return value.every(function (val) { return validate$q(val, [length]); }); } return string(value).length >= length; }; var min$1 = { validate: validate$q }; var validate$r = function (value, ref) { var min = ref[0]; if (value === null || value === undefined || value === '') { return false; } if (array.isarray(value)) { return value.length > 0 && value.every(function (val) { return validate$r(val, [min]); }); } return number(value) >= min; }; var min_value = { validate: validate$r }; var validate$s = function (value) { if (array.isarray(value)) { return value.every(function (val) { return /^[0-9]+$/.test(string(val)); }); } return /^[0-9]+$/.test(string(value)); }; var numeric = { validate: validate$s }; var validate$t = function (value, ref) { var expression = ref.expression; if (typeof expression === 'string') { expression = new regexp(expression); } return expression.test(string(value)); }; var paramnames$c = ['expression']; var regex = { validate: validate$t, paramnames: paramnames$c }; var validate$u = function (value, ref) { if ( ref === void 0 ) ref = []; var invalidatefalse = ref[0]; if ( invalidatefalse === void 0 ) invalidatefalse = false; if (array.isarray(value)) { return !!value.length; } // incase a field considers `false` as an empty value like checkboxes. if (value === false && invalidatefalse) { return false; } if (value === undefined || value === null) { return false; } return !!string(value).trim().length; }; var required = { validate: validate$u }; var validate$v = function (files, ref) { var size = ref[0]; if (isnan(size)) { return false; } var nsize = number(size) * 1024; for (var i = 0; i < files.length; i++) { if (files[i].size > nsize) { return false; } } return true; }; var size = { validate: validate$v }; var isurl_1 = createcommonjsmodule(function (module, exports) { object.defineproperty(exports, "__esmodule", { value: true }); exports.default = isurl; var _assertstring2 = _interoprequiredefault(assertstring_1); var _isfqdn2 = _interoprequiredefault(isfqdn_1); var _isip2 = _interoprequiredefault(isip_1); var _merge2 = _interoprequiredefault(merge_1); function _interoprequiredefault(obj) { return obj && obj.__esmodule ? obj : { default: obj }; } var default_url_options = { protocols: ['http', 'https', 'ftp'], require_tld: true, require_protocol: false, require_host: true, require_valid_protocol: true, allow_underscores: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }; var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/; function isregexp(obj) { return object.prototype.tostring.call(obj) === '[object regexp]'; } function checkhost(host, matches) { for (var i = 0; i < matches.length; i++) { var match = matches[i]; if (host === match || isregexp(match) && match.test(host)) { return true; } } return false; } function isurl(url, options) { (0, _assertstring2.default)(url); if (!url || url.length >= 2083 || /[\s<>]/.test(url)) { return false; } if (url.indexof('mailto:') === 0) { return false; } options = (0, _merge2.default)(options, default_url_options); var protocol = void 0, auth = void 0, host = void 0, hostname = void 0, port = void 0, port_str = void 0, split = void 0, ipv6 = void 0; split = url.split('#'); url = split.shift(); split = url.split('?'); url = split.shift(); split = url.split('://'); if (split.length > 1) { protocol = split.shift().tolowercase(); if (options.require_valid_protocol && options.protocols.indexof(protocol) === -1) { return false; } } else if (options.require_protocol) { return false; } else if (url.substr(0, 2) === '//') { if (!options.allow_protocol_relative_urls) { return false; } split[0] = url.substr(2); } url = split.join('://'); if (url === '') { return false; } split = url.split('/'); url = split.shift(); if (url === '' && !options.require_host) { return true; } split = url.split('@'); if (split.length > 1) { auth = split.shift(); if (auth.indexof(':') >= 0 && auth.split(':').length > 2) { return false; } } hostname = split.join('@'); port_str = null; ipv6 = null; var ipv6_match = hostname.match(wrapped_ipv6); if (ipv6_match) { host = ''; ipv6 = ipv6_match[1]; port_str = ipv6_match[2] || null; } else { split = hostname.split(':'); host = split.shift(); if (split.length) { port_str = split.join(':'); } } if (port_str !== null) { port = parseint(port_str, 10); if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { return false; } } if (!(0, _isip2.default)(host) && !(0, _isfqdn2.default)(host, options) && (!ipv6 || !(0, _isip2.default)(ipv6, 6))) { return false; } host = host || ipv6; if (options.host_whitelist && !checkhost(host, options.host_whitelist)) { return false; } if (options.host_blacklist && checkhost(host, options.host_blacklist)) { return false; } return true; } module.exports = exports['default']; }); var isurl = unwrapexports(isurl_1); var validate$w = function (value, options) { if ( options === void 0 ) options = {}; if (isnullorundefined(value)) { value = ''; } if (array.isarray(value)) { return value.every(function (val) { return isurl(val, options); }); } return isurl(value, options); }; var url = { validate: validate$w }; /* eslint-disable camelcase */ var rules = /*#__pure__*/object.freeze({ after: after, alpha_dash: alpha_dash, alpha_num: alpha_num, alpha_spaces: alpha_spaces, alpha: alpha$1, before: before, between: between, confirmed: confirmed, credit_card: credit_card, date_between: date_between, date_format: date_format, decimal: decimal, digits: digits, dimensions: dimensions, email: email, ext: ext, image: image, included: included, integer: integer, length: length, ip: ip, is_not: is_not, is: is, max: max$1, max_value: max_value, mimes: mimes, min: min$1, min_value: min_value, excluded: excluded, numeric: numeric, regex: regex, required: required, size: size, url: url }); /** * formates file size. * * @param {number|string} size */ var formatfilesize = function (size) { var units = ['byte', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']; var threshold = 1024; size = number(size) * threshold; var i = size === 0 ? 0 : math.floor(math.log(size) / math.log(threshold)); return (((size / math.pow(threshold, i)).tofixed(2) * 1) + " " + (units[i])); }; /** * checks if vee-validate is defined globally. */ var isdefinedglobally = function () { return typeof veevalidate !== 'undefined'; }; var obj; var messages = { _default: function (field) { return ("the " + field + " value is not valid."); }, after: function (field, ref) { var target = ref[0]; var inclusion = ref[1]; return ("the " + field + " must be after " + (inclusion ? 'or equal to ' : '') + target + "."); }, alpha_dash: function (field) { return ("the " + field + " field may contain alpha-numeric characters as well as dashes and underscores."); }, alpha_num: function (field) { return ("the " + field + " field may only contain alpha-numeric characters."); }, alpha_spaces: function (field) { return ("the " + field + " field may only contain alphabetic characters as well as spaces."); }, alpha: function (field) { return ("the " + field + " field may only contain alphabetic characters."); }, before: function (field, ref) { var target = ref[0]; var inclusion = ref[1]; return ("the " + field + " must be before " + (inclusion ? 'or equal to ' : '') + target + "."); }, between: function (field, ref) { var min = ref[0]; var max = ref[1]; return ("the " + field + " field must be between " + min + " and " + max + "."); }, confirmed: function (field) { return ("the " + field + " confirmation does not match."); }, credit_card: function (field) { return ("the " + field + " field is invalid."); }, date_between: function (field, ref) { var min = ref[0]; var max = ref[1]; return ("the " + field + " must be between " + min + " and " + max + "."); }, date_format: function (field, ref) { var format = ref[0]; return ("the " + field + " must be in the format " + format + "."); }, decimal: function (field, ref) { if ( ref === void 0 ) ref = []; var decimals = ref[0]; if ( decimals === void 0 ) decimals = '*'; return ("the " + field + " field must be numeric and may contain " + (!decimals || decimals === '*' ? '' : decimals) + " decimal points."); }, digits: function (field, ref) { var length = ref[0]; return ("the " + field + " field must be numeric and exactly contain " + length + " digits."); }, dimensions: function (field, ref) { var width = ref[0]; var height = ref[1]; return ("the " + field + " field must be " + width + " pixels by " + height + " pixels."); }, email: function (field) { return ("the " + field + " field must be a valid email."); }, ext: function (field) { return ("the " + field + " field must be a valid file."); }, image: function (field) { return ("the " + field + " field must be an image."); }, included: function (field) { return ("the " + field + " field must be a valid value."); }, integer: function (field) { return ("the " + field + " field must be an integer."); }, ip: function (field) { return ("the " + field + " field must be a valid ip address."); }, length: function (field, ref) { var length = ref[0]; var max = ref[1]; if (max) { return ("the " + field + " length must be between " + length + " and " + max + "."); } return ("the " + field + " length must be " + length + "."); }, max: function (field, ref) { var length = ref[0]; return ("the " + field + " field may not be greater than " + length + " characters."); }, max_value: function (field, ref) { var max = ref[0]; return ("the " + field + " field must be " + max + " or less."); }, mimes: function (field) { return ("the " + field + " field must have a valid file type."); }, min: function (field, ref) { var length = ref[0]; return ("the " + field + " field must be at least " + length + " characters."); }, min_value: function (field, ref) { var min = ref[0]; return ("the " + field + " field must be " + min + " or more."); }, excluded: function (field) { return ("the " + field + " field must be a valid value."); }, numeric: function (field) { return ("the " + field + " field may only contain numeric characters."); }, regex: function (field) { return ("the " + field + " field format is invalid."); }, required: function (field) { return ("the " + field + " field is required."); }, size: function (field, ref) { var size = ref[0]; return ("the " + field + " size must be less than " + (formatfilesize(size)) + "."); }, url: function (field) { return ("the " + field + " field is not a valid url."); } }; var locale$1 = { name: 'en', messages: messages, attributes: {} }; if (isdefinedglobally()) { // eslint-disable-next-line veevalidate.validator.localize(( obj = {}, obj[locale$1.name] = locale$1, obj )); } // var locale = 'en'; var dictionary = function dictionary (dictionary) { if ( dictionary === void 0 ) dictionary = {}; this.container = {}; this.merge(dictionary); }; var prototypeaccessors = { locale: { configurable: true } }; prototypeaccessors.locale.get = function () { return locale; }; prototypeaccessors.locale.set = function (value) { locale = value || 'en'; }; dictionary.prototype.haslocale = function haslocale (locale) { return !!this.container[locale]; }; dictionary.prototype.setdateformat = function setdateformat (locale, format) { if (!this.container[locale]) { this.container[locale] = {}; } this.container[locale].dateformat = format; }; dictionary.prototype.getdateformat = function getdateformat (locale) { if (!this.container[locale] || !this.container[locale].dateformat) { return null; } return this.container[locale].dateformat; }; dictionary.prototype.getmessage = function getmessage (locale, key, data) { var message = null; if (!this.hasmessage(locale, key)) { message = this._getdefaultmessage(locale); } else { message = this.container[locale].messages[key]; } return iscallable(message) ? message.apply(void 0, data) : message; }; /** * gets a specific message for field. falls back to the rule message. */ dictionary.prototype.getfieldmessage = function getfieldmessage (locale, field, key, data) { if (!this.haslocale(locale)) { return this.getmessage(locale, key, data); } var dict = this.container[locale].custom && this.container[locale].custom[field]; if (!dict || !dict[key]) { return this.getmessage(locale, key, data); } var message = dict[key]; return iscallable(message) ? message.apply(void 0, data) : message; }; dictionary.prototype._getdefaultmessage = function _getdefaultmessage (locale) { if (this.hasmessage(locale, '_default')) { return this.container[locale].messages._default; } return this.container.en.messages._default; }; dictionary.prototype.getattribute = function getattribute (locale, key, fallback) { if ( fallback === void 0 ) fallback = ''; if (!this.hasattribute(locale, key)) { return fallback; } return this.container[locale].attributes[key]; }; dictionary.prototype.hasmessage = function hasmessage (locale, key) { return !! ( this.haslocale(locale) && this.container[locale].messages && this.container[locale].messages[key] ); }; dictionary.prototype.hasattribute = function hasattribute (locale, key) { return !! ( this.haslocale(locale) && this.container[locale].attributes && this.container[locale].attributes[key] ); }; dictionary.prototype.merge = function merge$1$$1 (dictionary) { merge$1(this.container, dictionary); }; dictionary.prototype.setmessage = function setmessage (locale, key, message) { if (! this.haslocale(locale)) { this.container[locale] = { messages: {}, attributes: {} }; } this.container[locale].messages[key] = message; }; dictionary.prototype.setattribute = function setattribute (locale, key, attribute) { if (! this.haslocale(locale)) { this.container[locale] = { messages: {}, attributes: {} }; } this.container[locale].attributes[key] = attribute; }; object.defineproperties( dictionary.prototype, prototypeaccessors ); // var normalizevalue = function (value) { if (isobject(value)) { return object.keys(value).reduce(function (prev, key) { prev[key] = normalizevalue(value[key]); return prev; }, {}); } if (iscallable(value)) { return value('{0}', ['{1}', '{2}', '{3}']); } return value; }; var normalizeformat = function (locale) { // normalize messages var dictionary = {}; if (locale.messages) { dictionary.messages = normalizevalue(locale.messages); } if (locale.custom) { dictionary.custom = normalizevalue(locale.custom); } if (locale.attributes) { dictionary.attributes = locale.attributes; } if (!isnullorundefined(locale.dateformat)) { dictionary.dateformat = locale.dateformat; } return dictionary; }; var i18ndictionary = function i18ndictionary (i18n, rootkey) { this.i18n = i18n; this.rootkey = rootkey; }; var prototypeaccessors$1 = { locale: { configurable: true } }; prototypeaccessors$1.locale.get = function () { return this.i18n.locale; }; prototypeaccessors$1.locale.set = function (value) { warn('cannot set locale from the validator when using vue-i18n, use i18n.locale setter instead'); }; i18ndictionary.prototype.getdateformat = function getdateformat (locale) { return this.i18n.getdatetimeformat(locale || this.locale); }; i18ndictionary.prototype.setdateformat = function setdateformat (locale, value) { this.i18n.setdatetimeformat(locale || this.locale, value); }; i18ndictionary.prototype.getmessage = function getmessage (locale, key, data) { var path = (this.rootkey) + ".messages." + key; if (!this.i18n.te(path)) { return this.i18n.t(((this.rootkey) + ".messages._default"), locale, data); } return this.i18n.t(path, locale, data); }; i18ndictionary.prototype.getattribute = function getattribute (locale, key, fallback) { if ( fallback === void 0 ) fallback = ''; var path = (this.rootkey) + ".attributes." + key; if (!this.i18n.te(path)) { return fallback; } return this.i18n.t(path, locale); }; i18ndictionary.prototype.getfieldmessage = function getfieldmessage (locale, field, key, data) { var path = (this.rootkey) + ".custom." + field + "." + key; if (this.i18n.te(path)) { return this.i18n.t(path, locale, data); } return this.getmessage(locale, key, data); }; i18ndictionary.prototype.merge = function merge$1$$1 (dictionary) { var this$1 = this; object.keys(dictionary).foreach(function (localekey) { var obj; // i18n doesn't deep merge // first clone the existing locale (avoid mutations to locale) var clone = merge$1({}, getpath((localekey + "." + (this$1.rootkey)), this$1.i18n.messages, {})); // merge cloned locale with new one var locale = merge$1(clone, normalizeformat(dictionary[localekey])); this$1.i18n.mergelocalemessage(localekey, ( obj = {}, obj[this$1.rootkey] = locale, obj )); if (locale.dateformat) { this$1.i18n.setdatetimeformat(localekey, locale.dateformat); } }); }; i18ndictionary.prototype.setmessage = function setmessage (locale, key, value) { var obj, obj$1; this.merge(( obj$1 = {}, obj$1[locale] = { messages: ( obj = {}, obj[key] = value, obj ) }, obj$1 )); }; i18ndictionary.prototype.setattribute = function setattribute (locale, key, value) { var obj, obj$1; this.merge(( obj$1 = {}, obj$1[locale] = { attributes: ( obj = {}, obj[key] = value, obj ) }, obj$1 )); }; object.defineproperties( i18ndictionary.prototype, prototypeaccessors$1 ); // var defaultconfig = { locale: 'en', delay: 0, errorbagname: 'errors', dictionary: null, strict: true, fieldsbagname: 'fields', classes: false, classnames: null, events: 'input', inject: true, fastexit: true, aria: true, validity: false, i18n: null, i18nrootkey: 'validation' }; var currentconfig = assign({}, defaultconfig); var dependencies = { dictionary: new dictionary({ en: { messages: {}, attributes: {}, custom: {} } }) }; var config = function config () {}; var staticaccessors = { default: { configurable: true },current: { configurable: true } }; staticaccessors.default.get = function () { return defaultconfig; }; staticaccessors.current.get = function () { return currentconfig; }; config.dependency = function dependency (key) { return dependencies[key]; }; /** * merges the config with a new one. */ config.merge = function merge (config) { currentconfig = assign({}, currentconfig, config); if (currentconfig.i18n) { config.register('dictionary', new i18ndictionary(currentconfig.i18n, currentconfig.i18nrootkey)); } }; /** * registers a dependency. */ config.register = function register (key, value) { dependencies[key] = value; }; /** * resolves the working config from a vue instance. */ config.resolve = function resolve (context) { var selfconfig = getpath('$options.$_veevalidate', context, {}); return assign({}, config.current, selfconfig); }; object.defineproperties( config, staticaccessors ); // var errorbag = function errorbag (errorbag, id) { if ( errorbag === void 0 ) errorbag = null; if ( id === void 0 ) id = null; this.vmid = id || null; // make this bag a mirror of the provided one, sharing the same items reference. if (errorbag && errorbag instanceof errorbag) { this.items = errorbag.items; } else { this.items = []; } }; errorbag.prototype[typeof symbol === 'function' ? symbol.iterator : '@@iterator'] = function () { var this$1 = this; var index = 0; return { next: function () { return { value: this$1.items[index++], done: index > this$1.items.length }; } }; }; /** * adds an error to the internal array. */ errorbag.prototype.add = function add (error) { var ref; (ref = this.items).push.apply( ref, this._normalizeerror(error) ); }; /** * normalizes passed errors to an error array. */ errorbag.prototype._normalizeerror = function _normalizeerror (error) { var this$1 = this; if (array.isarray(error)) { return error.map(function (e) { e.scope = !isnullorundefined(e.scope) ? e.scope : null; e.vmid = !isnullorundefined(e.vmid) ? e.vmid : (this$1.vmid || null); return e; }); } error.scope = !isnullorundefined(error.scope) ? error.scope : null; error.vmid = !isnullorundefined(error.vmid) ? error.vmid : (this.vmid || null); return [error]; }; /** * regenrates error messages if they have a generator function. */ errorbag.prototype.regenerate = function regenerate () { this.items.foreach(function (i) { i.msg = iscallable(i.regenerate) ? i.regenerate() : i.msg; }); }; /** * updates a field error with the new field scope. */ errorbag.prototype.update = function update (id, error) { var item = find(this.items, function (i) { return i.id === id; }); if (!item) { return; } var idx = this.items.indexof(item); this.items.splice(idx, 1); item.scope = error.scope; this.items.push(item); }; /** * gets all error messages from the internal array. */ errorbag.prototype.all = function all (scope) { var this$1 = this; var filterfn = function (item) { var matchesscope = true; var matchesvm = true; if (!isnullorundefined(scope)) { matchesscope = item.scope === scope; } if (!isnullorundefined(this$1.vmid)) { matchesvm = item.vmid === this$1.vmid; } return matchesvm && matchesscope; }; return this.items.filter(filterfn).map(function (e) { return e.msg; }); }; /** * checks if there are any errors in the internal array. */ errorbag.prototype.any = function any (scope) { var this$1 = this; var filterfn = function (item) { var matchesscope = true; if (!isnullorundefined(scope)) { matchesscope = item.scope === scope; } if (!isnullorundefined(this$1.vmid)) { matchesscope = item.vmid === this$1.vmid; } return matchesscope; }; return !!this.items.filter(filterfn).length; }; /** * removes all items from the internal array. */ errorbag.prototype.clear = function clear (scope) { var this$1 = this; var matchesvm = isnullorundefined(this.vmid) ? function () { return true; } : function (i) { return i.vmid === this$1.vmid; }; if (isnullorundefined(scope)) { scope = null; } for (var i = 0; i < this.items.length; ++i) { if (matchesvm(this$1.items[i]) && this$1.items[i].scope === scope) { this$1.items.splice(i, 1); --i; } } }; /** * collects errors into groups or for a specific field. */ errorbag.prototype.collect = function collect (field, scope, map) { var this$1 = this; if ( map === void 0 ) map = true; var issinglefield = !isnullorundefined(field) && !field.includes('*'); var grouperrors = function (items) { var errors = items.reduce(function (collection, error) { if (!isnullorundefined(this$1.vmid) && error.vmid !== this$1.vmid) { return collection; } if (!collection[error.field]) { collection[error.field] = []; } collection[error.field].push(map ? error.msg : error); return collection; }, {}); // reduce the collection to be a single array. if (issinglefield) { return values(errors)[0] || []; } return errors; }; if (isnullorundefined(field)) { return grouperrors(this.items); } var selector = isnullorundefined(scope) ? string(field) : (scope + "." + field); var ref = this._makecandidatefilters(selector); var isprimary = ref.isprimary; var isalt = ref.isalt; var collected = this.items.reduce(function (prev, curr) { if (isprimary(curr)) { prev.primary.push(curr); } if (isalt(curr)) { prev.alt.push(curr); } return prev; }, { primary: [], alt: [] }); collected = collected.primary.length ? collected.primary : collected.alt; return grouperrors(collected); }; /** * gets the internal array length. */ errorbag.prototype.count = function count () { var this$1 = this; if (this.vmid) { return this.items.filter(function (e) { return e.vmid === this$1.vmid; }).length; } return this.items.length; }; /** * finds and fetches the first error message for the specified field id. */ errorbag.prototype.firstbyid = function firstbyid (id) { var error = find(this.items, function (i) { return i.id === id; }); return error ? error.msg : undefined; }; /** * gets the first error message for a specific field. */ errorbag.prototype.first = function first (field, scope) { if ( scope === void 0 ) scope = null; var selector = isnullorundefined(scope) ? field : (scope + "." + field); var match = this._match(selector); return match && match.msg; }; /** * returns the first error rule for the specified field */ errorbag.prototype.firstrule = function firstrule (field, scope) { var errors = this.collect(field, scope, false); return (errors.length && errors[0].rule) || undefined; }; /** * checks if the internal array has at least one error for the specified field. */ errorbag.prototype.has = function has (field, scope) { if ( scope === void 0 ) scope = null; return !!this.first(field, scope); }; /** * gets the first error message for a specific field and a rule. */ errorbag.prototype.firstbyrule = function firstbyrule (name, rule, scope) { if ( scope === void 0 ) scope = null; var error = this.collect(name, scope, false).filter(function (e) { return e.rule === rule; })[0]; return (error && error.msg) || undefined; }; /** * gets the first error message for a specific field that not match the rule. */ errorbag.prototype.firstnot = function firstnot (name, rule, scope) { if ( rule === void 0 ) rule = 'required'; if ( scope === void 0 ) scope = null; var error = this.collect(name, scope, false).filter(function (e) { return e.rule !== rule; })[0]; return (error && error.msg) || undefined; }; /** * removes errors by matching against the id or ids. */ errorbag.prototype.removebyid = function removebyid (id) { var this$1 = this; var condition = function (item) { return item.id === id; }; if (array.isarray(id)) { condition = function (item) { return id.indexof(item.id) !== -1; }; } for (var i = 0; i < this.items.length; ++i) { if (condition(this$1.items[i])) { this$1.items.splice(i, 1); --i; } } }; /** * removes all error messages associated with a specific field. */ errorbag.prototype.remove = function remove (field, scope, vmid) { var this$1 = this; if (isnullorundefined(field)) { return; } var selector = isnullorundefined(scope) ? string(field) : (scope + "." + field); var ref = this._makecandidatefilters(selector); var isprimary = ref.isprimary; var shouldremove = function (item) { if (isnullorundefined(vmid)) { return isprimary(item); } return isprimary(item) && item.vmid === vmid; }; for (var i = 0; i < this.items.length; ++i) { if (shouldremove(this$1.items[i])) { this$1.items.splice(i, 1); --i; } } }; errorbag.prototype._makecandidatefilters = function _makecandidatefilters (selector) { var this$1 = this; var matchesrule = function () { return true; }; var matchesscope = function () { return true; }; var matchesname = function () { return true; }; var matchesvm = function () { return true; }; var ref = parseselector(selector); var id = ref.id; var rule = ref.rule; var scope = ref.scope; var name = ref.name; if (rule) { matchesrule = function (item) { return item.rule === rule; }; } // match by id, can be combined with rule selection. if (id) { return { isprimary: function (item) { return matchesrule(item) && (function (item) { return id === item.id; }); }, isalt: function () { return false; } }; } if (isnullorundefined(scope)) { // if no scope specified, make sure the found error has no scope. matchesscope = function (item) { return isnullorundefined(item.scope); }; } else { matchesscope = function (item) { return item.scope === scope; }; } if (!isnullorundefined(name) && name !== '*') { matchesname = function (item) { return item.field === name; }; } if (!isnullorundefined(this.vmid)) { matchesvm = function (item) { return item.vmid === this$1.vmid; }; } // matches the first candidate. var isprimary = function (item) { return matchesvm(item) && matchesname(item) && matchesrule(item) && matchesscope(item); }; // matches a second candidate, which is a field with a name containing the '.' character. var isalt = function (item) { return matchesvm(item) && matchesrule(item) && item.field === (scope + "." + name); }; return { isprimary: isprimary, isalt: isalt }; }; errorbag.prototype._match = function _match (selector) { if (isnullorundefined(selector)) { return undefined; } var ref = this._makecandidatefilters(selector); var isprimary = ref.isprimary; var isalt = ref.isalt; return this.items.reduce(function (prev, item, idx, arr) { var islast = idx === arr.length - 1; if (prev.primary) { return islast ? prev.primary : prev; } if (isprimary(item)) { prev.primary = item; } if (isalt(item)) { prev.alt = item; } // keep going. if (!islast) { return prev; } return prev.primary || prev.alt; }, {}); }; /** * generates the options required to construct a field. */ var resolver = function resolver () {}; resolver.generate = function generate (el, binding, vnode) { var model = resolver.resolvemodel(binding, vnode); var options = config.resolve(vnode.context); return { name: resolver.resolvename(el, vnode), el: el, listen: !binding.modifiers.disable, bails: binding.modifiers.bails ? true : (binding.modifiers.continues === true ? false : undefined), scope: resolver.resolvescope(el, binding, vnode), vm: resolver.makevm(vnode.context), expression: binding.value, component: vnode.componentinstance, classes: options.classes, classnames: options.classnames, getter: resolver.resolvegetter(el, vnode, model), events: resolver.resolveevents(el, vnode) || options.events, model: model, delay: resolver.resolvedelay(el, vnode, options), rules: resolver.resolverules(el, binding, vnode), immediate: !!binding.modifiers.initial || !!binding.modifiers.immediate, validity: options.validity, aria: options.aria, initialvalue: resolver.resolveinitialvalue(vnode) }; }; resolver.getctorconfig = function getctorconfig (vnode) { if (!vnode.componentinstance) { return null; } var config = getpath('componentinstance.$options.$_veevalidate', vnode); return config; }; /** * resolves the rules defined on an element. */ resolver.resolverules = function resolverules (el, binding, vnode) { var rules = ''; if (!binding.value && (!binding || !binding.expression)) { rules = getdataattribute(el, 'rules'); } if (binding.value && includes(['string', 'object'], typeof binding.value.rules)) { rules = binding.value.rules; } else if (binding.value) { rules = binding.value; } if (vnode.componentinstance) { return rules; } return fillrulesfromelement(el, rules); }; /** * @param {*} vnode */ resolver.resolveinitialvalue = function resolveinitialvalue (vnode) { var model = vnode.data.model || find(vnode.data.directives, function (d) { return d.name === 'model'; }); return model && model.value; }; /** * creates a non-circular partial vm instance from a vue instance. * @param {*} vm */ resolver.makevm = function makevm (vm) { return { get $el () { return vm.$el; }, get $refs () { return vm.$refs; }, $watch: vm.$watch ? vm.$watch.bind(vm) : function () {}, $validator: vm.$validator ? { errors: vm.$validator.errors, validate: vm.$validator.validate.bind(vm.$validator), update: vm.$validator.update.bind(vm.$validator) } : null }; }; /** * resolves the delay value. * @param {*} el * @param {*} vnode * @param {object} options */ resolver.resolvedelay = function resolvedelay (el, vnode, options) { var delay = getdataattribute(el, 'delay'); var globaldelay = (options && 'delay' in options) ? options.delay : 0; if (!delay && vnode.componentinstance && vnode.componentinstance.$attrs) { delay = vnode.componentinstance.$attrs['data-vv-delay']; } if (!isobject(globaldelay)) { return deepparseint(delay || globaldelay); } if (!isnullorundefined(delay)) { globaldelay.input = delay; } return deepparseint(globaldelay); }; /** * resolves the events to validate in response to. * @param {*} el * @param {*} vnode */ resolver.resolveevents = function resolveevents (el, vnode) { // resolve it from the root element. var events = getdataattribute(el, 'validate-on'); // resolve from data-vv-validate-on if its a vue component. if (!events && vnode.componentinstance && vnode.componentinstance.$attrs) { events = vnode.componentinstance.$attrs['data-vv-validate-on']; } // resolve it from $_veevalidate options. if (!events && vnode.componentinstance) { var config = resolver.getctorconfig(vnode); events = config && config.events; } if (!events && config.current.events) { events = config.current.events; } // resolve the model event if its configured for custom components. if (events && vnode.componentinstance && includes(events, 'input')) { var ref = vnode.componentinstance.$options.model || { event: 'input' }; var event = ref.event; // if the prop was configured but not the model. if (!event) { return events; } events = events.replace('input', event); } return events; }; /** * resolves the scope for the field. * @param {*} el * @param {*} binding */ resolver.resolvescope = function resolvescope (el, binding, vnode) { if ( vnode === void 0 ) vnode = {}; var scope = null; if (vnode.componentinstance && isnullorundefined(scope)) { scope = vnode.componentinstance.$attrs && vnode.componentinstance.$attrs['data-vv-scope']; } return !isnullorundefined(scope) ? scope : getscope(el); }; /** * checks if the node directives contains a v-model or a specified arg. * args take priority over models. * * @return {object} */ resolver.resolvemodel = function resolvemodel (binding, vnode) { if (binding.arg) { return { expression: binding.arg }; } var model = vnode.data.model || find(vnode.data.directives, function (d) { return d.name === 'model'; }); if (!model) { return null; } // https://github.com/vuejs/vue/blob/dev/src/core/util/lang.js#l26 var watchable = !/[^\w.$]/.test(model.expression) && haspath(model.expression, vnode.context); var lazy = !!(model.modifiers && model.modifiers.lazy); if (!watchable) { return { expression: null, lazy: lazy }; } return { expression: model.expression, lazy: lazy }; }; /** * resolves the field name to trigger validations. * @return {string} the field name. */ resolver.resolvename = function resolvename (el, vnode) { var name = getdataattribute(el, 'name'); if (!name && !vnode.componentinstance) { return el.name; } if (!name && vnode.componentinstance && vnode.componentinstance.$attrs) { name = vnode.componentinstance.$attrs['data-vv-name'] || vnode.componentinstance.$attrs['name']; } if (!name && vnode.componentinstance) { var config = resolver.getctorconfig(vnode); if (config && iscallable(config.name)) { var boundgetter = config.name.bind(vnode.componentinstance); return boundgetter(); } return vnode.componentinstance.name; } return name; }; /** * returns a value getter input type. */ resolver.resolvegetter = function resolvegetter (el, vnode, model) { if (model && model.expression) { return function () { return getpath(model.expression, vnode.context); }; } if (vnode.componentinstance) { var path = getdataattribute(el, 'value-path') || (vnode.componentinstance.$attrs && vnode.componentinstance.$attrs['data-vv-value-path']); if (path) { return function () { return getpath(path, vnode.componentinstance); }; } var config = resolver.getctorconfig(vnode); if (config && iscallable(config.value)) { var boundgetter = config.value.bind(vnode.componentinstance); return function () { return boundgetter(); }; } var ref = vnode.componentinstance.$options.model || { prop: 'value' }; var prop = ref.prop; return function () { return vnode.componentinstance[prop]; }; } switch (el.type) { case 'checkbox': return function () { var els = document.queryselectorall(("input[name=\"" + (el.name) + "\"]")); els = toarray(els).filter(function (el) { return el.checked; }); if (!els.length) { return undefined; } return els.map(function (checkbox) { return checkbox.value; }); }; case 'radio': return function () { var els = document.queryselectorall(("input[name=\"" + (el.name) + "\"]")); var elm = find(els, function (el) { return el.checked; }); return elm && elm.value; }; case 'file': return function (context) { return toarray(el.files); }; case 'select-multiple': return function () { return toarray(el.options).filter(function (opt) { return opt.selected; }).map(function (opt) { return opt.value; }); }; default: return function () { return el && el.value; }; } }; // var rules = {}; var strict_mode = true; var validator = function validator (validations, options) { if ( options === void 0 ) options = { fastexit: true }; this.strict = strict_mode; this.errors = new errorbag(); this.fields = new fieldbag(); this._createfields(validations); this.paused = false; this.fastexit = !isnullorundefined(options && options.fastexit) ? options.fastexit : true; }; var prototypeaccessors$2 = { rules: { configurable: true },flags: { configurable: true },dictionary: { configurable: true },_vm: { configurable: true },locale: { configurable: true } }; var staticaccessors$1 = { rules: { configurable: true },dictionary: { configurable: true },locale: { configurable: true } }; staticaccessors$1.rules.get = function () { return rules; }; prototypeaccessors$2.rules.get = function () { return rules; }; prototypeaccessors$2.flags.get = function () { return this.fields.items.reduce(function (acc, field) { var obj; if (field.scope) { acc[("$" + (field.scope))] = ( obj = {}, obj[field.name] = field.flags, obj ); return acc; } acc[field.name] = field.flags; return acc; }, {}); }; /** * getter for the dictionary. */ prototypeaccessors$2.dictionary.get = function () { return config.dependency('dictionary'); }; staticaccessors$1.dictionary.get = function () { return config.dependency('dictionary'); }; prototypeaccessors$2._vm.get = function () { return config.dependency('vm'); }; /** * getter for the current locale. */ prototypeaccessors$2.locale.get = function () { return validator.locale; }; /** * setter for the validator locale. */ prototypeaccessors$2.locale.set = function (value) { validator.locale = value; }; staticaccessors$1.locale.get = function () { return this.dictionary.locale; }; /** * setter for the validator locale. */ staticaccessors$1.locale.set = function (value) { var haschanged = value !== validator.dictionary.locale; validator.dictionary.locale = value; if (haschanged && config.dependency('vm')) { config.dependency('vm').$emit('localechanged'); } }; /** * static constructor. */ validator.create = function create (validations, options) { return new validator(validations, options); }; /** * adds a custom validator to the list of validation rules. */ validator.extend = function extend (name, validator, options) { if ( options === void 0 ) options = {}; validator._guardextend(name, validator); validator._merge(name, { validator: validator, paramnames: options && options.paramnames, options: assign({}, { hastarget: false, immediate: true }, options || {}) }); }; /** * removes a rule from the list of validators. */ validator.remove = function remove (name) { delete rules[name]; }; /** * checks if the given rule name is a rule that targets other fields. */ validator.istargetrule = function istargetrule (name) { return !!rules[name] && rules[name].options.hastarget; }; /** * sets the operating mode for all newly created validators. * strictmode = true: values without a rule are invalid and cause failure. * strictmode = false: values without a rule are valid and are skipped. */ validator.setstrictmode = function setstrictmode (strictmode) { if ( strictmode === void 0 ) strictmode = true; strict_mode = strictmode; }; /** * adds and sets the current locale for the validator. */ validator.prototype.localize = function localize (lang, dictionary) { validator.localize(lang, dictionary); }; /** * adds and sets the current locale for the validator. */ validator.localize = function localize (lang, dictionary) { var obj; if (isobject(lang)) { validator.dictionary.merge(lang); return; } // merge the dictionary. if (dictionary) { var locale = lang || dictionary.name; dictionary = assign({}, dictionary); validator.dictionary.merge(( obj = {}, obj[locale] = dictionary, obj )); } if (lang) { // set the locale. validator.locale = lang; } }; /** * registers a field to be validated. */ validator.prototype.attach = function attach (fieldopts) { // fixes initial value detection with v-model and select elements. var value = fieldopts.initialvalue; var field = new field(fieldopts); this.fields.push(field); // validate the field initially if (field.immediate) { this.validate(("#" + (field.id)), value || field.value, { vmid: fieldopts.vmid }); } else { this._validate(field, value || field.value, { initial: true }).then(function (result) { field.flags.valid = result.valid; field.flags.invalid = !result.valid; }); } return field; }; /** * sets the flags on a field. */ validator.prototype.flag = function flag (name, flags, uid) { if ( uid === void 0 ) uid = null; var field = this._resolvefield(name, undefined, uid); if (!field || !flags) { return; } field.setflags(flags); }; /** * removes a field from the validator. */ validator.prototype.detach = function detach (name, scope, uid) { var field = iscallable(name.destroy) ? name : this._resolvefield(name, scope, uid); if (!field) { return; } field.destroy(); this.errors.remove(field.name, field.scope, field.vmid); this.fields.remove(field); }; /** * adds a custom validator to the list of validation rules. */ validator.prototype.extend = function extend (name, validator, options) { if ( options === void 0 ) options = {}; validator.extend(name, validator, options); }; validator.prototype.reset = function reset (matcher) { var this$1 = this; // two ticks return this._vm.$nexttick().then(function () { return this$1._vm.$nexttick(); }).then(function () { this$1.fields.filter(matcher).foreach(function (field) { field.reset(); // reset field flags. this$1.errors.remove(field.name, field.scope); }); }); }; /** * updates a field, updating both errors and flags. */ validator.prototype.update = function update (id, ref) { var scope = ref.scope; var field = this._resolvefield(("#" + id)); if (!field) { return; } // remove old scope. this.errors.update(id, { scope: scope }); }; /** * removes a rule from the list of validators. */ validator.prototype.remove = function remove (name) { validator.remove(name); }; /** * validates a value against a registered field validations. */ validator.prototype.validate = function validate (fielddescriptor, value, ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var silent = ref.silent; var vmid = ref.vmid; if (this.paused) { return promise.resolve(true); } // overload to validate all. if (isnullorundefined(fielddescriptor)) { return this.validatescopes({ silent: silent, vmid: vmid }); } // overload to validate scope-less fields. if (fielddescriptor === '*') { return this.validateall(undefined, { silent: silent, vmid: vmid }); } // if scope validation was requested. if (/^(.+)\.\*$/.test(fielddescriptor)) { var matched = fielddescriptor.match(/^(.+)\.\*$/)[1]; return this.validateall(matched); } var field = this._resolvefield(fielddescriptor); if (!field) { return this._handlefieldnotfound(name); } if (!silent) { field.flags.pending = true; } if (value === undefined) { value = field.value; } return this._validate(field, value).then(function (result) { if (!silent) { this$1._handlevalidationresults([result], vmid); } return result.valid; }); }; /** * pauses the validator. */ validator.prototype.pause = function pause () { this.paused = true; return this; }; /** * resumes the validator. */ validator.prototype.resume = function resume () { this.paused = false; return this; }; /** * validates each value against the corresponding field validations. */ validator.prototype.validateall = function validateall (values$$1, ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var silent = ref.silent; var vmid = ref.vmid; if (this.paused) { return promise.resolve(true); } var matcher = null; var providedvalues = false; if (typeof values$$1 === 'string') { matcher = { scope: values$$1, vmid: vmid }; } else if (isobject(values$$1)) { matcher = object.keys(values$$1).map(function (key) { return { name: key, vmid: vmid, scope: null }; }); providedvalues = true; } else if (array.isarray(values$$1)) { matcher = values$$1.map(function (key) { return { name: key, vmid: vmid }; }); } else { matcher = { scope: null, vmid: vmid }; } return promise.all( this.fields.filter(matcher).map(function (field) { return this$1._validate(field, providedvalues ? values$$1[field.name] : field.value); }) ).then(function (results) { if (!silent) { this$1._handlevalidationresults(results, vmid); } return results.every(function (t) { return t.valid; }); }); }; /** * validates all scopes. */ validator.prototype.validatescopes = function validatescopes (ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var silent = ref.silent; var vmid = ref.vmid; if (this.paused) { return promise.resolve(true); } return promise.all( this.fields.filter({ vmid: vmid }).map(function (field) { return this$1._validate(field, field.value); }) ).then(function (results) { if (!silent) { this$1._handlevalidationresults(results, vmid); } return results.every(function (t) { return t.valid; }); }); }; /** * validates a value against the rules. */ validator.prototype.verify = function verify (value, rules) { var field = { name: '{field}', rules: normalizerules(rules) }; field.isrequired = field.rules.required; return this._validate(field, value).then(function (result) { return { valid: result.valid, errors: result.errors.map(function (e) { return e.msg; }) }; }); }; /** * perform cleanup. */ validator.prototype.destroy = function destroy () { this._vm.$off('localechanged'); }; /** * creates the fields to be validated. */ validator.prototype._createfields = function _createfields (validations) { var this$1 = this; if (!validations) { return; } object.keys(validations).foreach(function (field) { var options = assign({}, { name: field, rules: validations[field] }); this$1.attach(options); }); }; /** * date rules need the existence of a format, so date_format must be supplied. */ validator.prototype._getdateformat = function _getdateformat (validations) { var format = null; if (validations.date_format && array.isarray(validations.date_format)) { format = validations.date_format[0]; } return format || this.dictionary.getdateformat(this.locale); }; /** * formats an error message for field and a rule. */ validator.prototype._formaterrormessage = function _formaterrormessage (field, rule, data, targetname) { if ( data === void 0 ) data = {}; if ( targetname === void 0 ) targetname = null; var name = this._getfielddisplayname(field); var params = this._getlocalizedparams(rule, targetname); return this.dictionary.getfieldmessage(this.locale, field.name, rule.name, [name, params, data]); }; /** * we need to convert any object param to an array format since the locales do not handle params as objects yet. */ validator.prototype._convertparamobjecttoarray = function _convertparamobjecttoarray (obj, rulename) { if (array.isarray(obj)) { return obj; } var paramnames = rules[rulename] && rules[rulename].paramnames; if (!paramnames || !isobject(obj)) { return obj; } return paramnames.reduce(function (prev, paramname) { if (paramname in obj) { prev.push(obj[paramname]); } return prev; }, []); }; /** * translates the parameters passed to the rule (mainly for target fields). */ validator.prototype._getlocalizedparams = function _getlocalizedparams (rule, targetname) { if ( targetname === void 0 ) targetname = null; var params = this._convertparamobjecttoarray(rule.params, rule.name); if (rule.options.hastarget && params && params[0]) { var localizedname = targetname || this.dictionary.getattribute(this.locale, params[0], params[0]); return [localizedname].concat(params.slice(1)); } return params; }; /** * resolves an appropriate display name, first checking 'data-as' or the registered 'prettyname' */ validator.prototype._getfielddisplayname = function _getfielddisplayname (field) { return field.alias || this.dictionary.getattribute(this.locale, field.name, field.name); }; /** * converts an array of params to an object with named properties. * only works if the rule is configured with a paramnames array. * returns the same params if it cannot convert it. */ validator.prototype._convertparamarraytoobj = function _convertparamarraytoobj (params, rulename) { var paramnames = rules[rulename] && rules[rulename].paramnames; if (!paramnames) { return params; } if (isobject(params)) { // check if the object is either a config object or a single parameter that is an object. var haskeys = paramnames.some(function (name) { return object.keys(params).indexof(name) !== -1; }); // if it has some of the keys, return it as is. if (haskeys) { return params; } // otherwise wrap the object in an array. params = [params]; } // reduce the paramsnames to a param object. return params.reduce(function (prev, value, idx) { prev[paramnames[idx]] = value; return prev; }, {}); }; /** * tests a single input value against a rule. */ validator.prototype._test = function _test (field, value, rule) { var this$1 = this; var validator = rules[rule.name] ? rules[rule.name].validate : null; var params = array.isarray(rule.params) ? toarray(rule.params) : rule.params; if (!params) { params = []; } var targetname = null; if (!validator || typeof validator !== 'function') { return promise.reject(createerror(("no such validator '" + (rule.name) + "' exists."))); } // has field dependencies. if (rule.options.hastarget) { var target = find(field.dependencies, function (d) { return d.name === rule.name; }); if (target) { targetname = target.field.alias; params = [target.field.value].concat(params.slice(1)); } } else if (rule.name === 'required' && field.rejectsfalse) { // invalidate false if no args were specified and the field rejects false by default. params = params.length ? params : [true]; } if (rule.options.isdate) { var dateformat = this._getdateformat(field.rules); if (rule.name !== 'date_format') { params.push(dateformat); } } var result = validator(value, this._convertparamarraytoobj(params, rule.name)); // if it is a promise. if (iscallable(result.then)) { return result.then(function (values$$1) { var allvalid = true; var data = {}; if (array.isarray(values$$1)) { allvalid = values$$1.every(function (t) { return (isobject(t) ? t.valid : t); }); } else { // is a single object/boolean. allvalid = isobject(values$$1) ? values$$1.valid : values$$1; data = values$$1.data; } return { valid: allvalid, errors: allvalid ? [] : [this$1._createfielderror(field, rule, data, targetname)] }; }); } if (!isobject(result)) { result = { valid: result, data: {} }; } return { valid: result.valid, errors: result.valid ? [] : [this._createfielderror(field, rule, result.data, targetname)] }; }; /** * merges a validator object into the rules and messages. */ validator._merge = function _merge (name, ref) { var validator = ref.validator; var options = ref.options; var paramnames = ref.paramnames; var validate = iscallable(validator) ? validator : validator.validate; if (validator.getmessage) { validator.dictionary.setmessage(validator.locale, name, validator.getmessage); } rules[name] = { validate: validate, options: options, paramnames: paramnames }; }; /** * guards from extension violations. */ validator._guardextend = function _guardextend (name, validator) { if (iscallable(validator)) { return; } if (!iscallable(validator.validate)) { throw createerror( ("extension error: the validator '" + name + "' must be a function or have a 'validate' method.") ); } }; /** * creates a field error object. */ validator.prototype._createfielderror = function _createfielderror (field, rule, data, targetname) { var this$1 = this; return { id: field.id, vmid: field.vmid, field: field.name, msg: this._formaterrormessage(field, rule, data, targetname), rule: rule.name, scope: field.scope, regenerate: function () { return this$1._formaterrormessage(field, rule, data, targetname); } }; }; /** * tries different strategies to find a field. */ validator.prototype._resolvefield = function _resolvefield (name, scope, uid) { if (name[0] === '#') { return this.fields.find({ id: name.slice(1) }); } if (!isnullorundefined(scope)) { return this.fields.find({ name: name, scope: scope, vmid: uid }); } if (includes(name, '.')) { var ref = name.split('.'); var fieldscope = ref[0]; var fieldname = ref.slice(1); var field = this.fields.find({ name: fieldname.join('.'), scope: fieldscope, vmid: uid }); if (field) { return field; } } return this.fields.find({ name: name, scope: null, vmid: uid }); }; /** * handles when a field is not found depending on the strict flag. */ validator.prototype._handlefieldnotfound = function _handlefieldnotfound (name, scope) { if (!this.strict) { return promise.resolve(true); } var fullname = isnullorundefined(scope) ? name : ("" + (!isnullorundefined(scope) ? scope + '.' : '') + name); return promise.reject(createerror( ("validating a non-existent field: \"" + fullname + "\". use \"attach()\" first.") )); }; /** * handles validation results. */ validator.prototype._handlevalidationresults = function _handlevalidationresults (results, vmid) { var this$1 = this; var matchers = results.map(function (result) { return ({ id: result.id }); }); this.errors.removebyid(matchers.map(function (m) { return m.id; })); // remove by name and scope to remove any custom errors added. results.foreach(function (result) { this$1.errors.remove(result.field, result.scope, vmid); }); var allerrors = results.reduce(function (prev, curr) { prev.push.apply(prev, curr.errors); return prev; }, []); this.errors.add(allerrors); // handle flags. this.fields.filter(matchers).foreach(function (field) { var result = find(results, function (r) { return r.id === field.id; }); field.setflags({ pending: false, valid: result.valid, validated: true }); }); }; validator.prototype._shouldskip = function _shouldskip (field, value) { // field is configured to run through the pipeline regardless if (field.bails === false) { return false; } // disabled fields are skipped if (field.isdisabled) { return true; } // skip if the field is not required and has an empty value. return !field.isrequired && (isnullorundefined(value) || value === ''); }; validator.prototype._shouldbail = function _shouldbail (field, value) { // if the field was configured explicitly. if (field.bails !== undefined) { return field.bails; } return this.fastexit; }; /** * starts the validation process. */ validator.prototype._validate = function _validate (field, value, ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var initial = ref.initial; if (this._shouldskip(field, value)) { return promise.resolve({ valid: true, id: field.id, field: field.name, scope: field.scope, errors: [] }); } var promises = []; var errors = []; var isexitearly = false; // use of '.some()' is to break iteration in middle by returning true object.keys(field.rules).filter(function (rule) { if (!initial || !rules[rule]) { return true; } return rules[rule].options.immediate; }).some(function (rule) { var ruleoptions = rules[rule] ? rules[rule].options : {}; var result = this$1._test(field, value, { name: rule, params: field.rules[rule], options: ruleoptions }); if (iscallable(result.then)) { promises.push(result); } else if (!result.valid && this$1._shouldbail(field, value)) { errors.push.apply(errors, result.errors); isexitearly = true; } else { // promisify the result. promises.push(new promise(function (resolve) { return resolve(result); })); } return isexitearly; }); if (isexitearly) { return promise.resolve({ valid: false, errors: errors, id: field.id, field: field.name, scope: field.scope }); } return promise.all(promises).then(function (results) { return results.reduce(function (prev, v) { var ref; if (!v.valid) { (ref = prev.errors).push.apply(ref, v.errors); } prev.valid = prev.valid && v.valid; return prev; }, { valid: true, errors: errors, id: field.id, field: field.name, scope: field.scope }); }); }; object.defineproperties( validator.prototype, prototypeaccessors$2 ); object.defineproperties( validator, staticaccessors$1 ); // var default_options = { targetof: null, immediate: false, scope: null, listen: true, name: null, rules: {}, vm: null, classes: false, validity: true, aria: true, events: 'input|blur', delay: 0, classnames: { touched: 'touched', // the control has been blurred untouched: 'untouched', // the control hasn't been blurred valid: 'valid', // model is valid invalid: 'invalid', // model is invalid pristine: 'pristine', // control has not been interacted with dirty: 'dirty' // control has been interacted with } }; var field = function field (options) { if ( options === void 0 ) options = {}; this.id = uniqid(); this.el = options.el; this.updated = false; this.dependencies = []; this.vmid = options.vmid; this.watchers = []; this.events = []; this.delay = 0; this.rules = {}; this._cacheid(options); this.classnames = assign({}, default_options.classnames); options = assign({}, default_options, options); this._delay = !isnullorundefined(options.delay) ? options.delay : 0; // cache initial delay this.validity = options.validity; this.aria = options.aria; this.flags = createflags(); this.vm = options.vm; this.componentinstance = options.component; this.ctorconfig = this.componentinstance ? getpath('$options.$_veevalidate', this.componentinstance) : undefined; this.update(options); // set initial value. this.initialvalue = this.value; this.updated = false; }; var prototypeaccessors$3 = { validator: { configurable: true },isrequired: { configurable: true },isdisabled: { configurable: true },alias: { configurable: true },value: { configurable: true },bails: { configurable: true },rejectsfalse: { configurable: true } }; prototypeaccessors$3.validator.get = function () { if (!this.vm || !this.vm.$validator) { return { validate: function () {} }; } return this.vm.$validator; }; prototypeaccessors$3.isrequired.get = function () { return !!this.rules.required; }; prototypeaccessors$3.isdisabled.get = function () { return !!(this.componentinstance && this.componentinstance.disabled) || !!(this.el && this.el.disabled); }; /** * gets the display name (user-friendly name). */ prototypeaccessors$3.alias.get = function () { if (this._alias) { return this._alias; } var alias = null; if (this.el) { alias = getdataattribute(this.el, 'as'); } if (!alias && this.componentinstance) { return this.componentinstance.$attrs && this.componentinstance.$attrs['data-vv-as']; } return alias; }; /** * gets the input value. */ prototypeaccessors$3.value.get = function () { if (!iscallable(this.getter)) { return undefined; } return this.getter(); }; prototypeaccessors$3.bails.get = function () { return this._bails; }; /** * if the field rejects false as a valid value for the required rule. */ prototypeaccessors$3.rejectsfalse.get = function () { if (this.componentinstance && this.ctorconfig) { return !!this.ctorconfig.rejectsfalse; } if (!this.el) { return false; } return this.el.type === 'checkbox'; }; /** * determines if the instance matches the options provided. */ field.prototype.matches = function matches (options) { var this$1 = this; if (!options) { return true; } if (options.id) { return this.id === options.id; } var matchescomponentid = isnullorundefined(options.vmid) ? function () { return true; } : function (id) { return id === this$1.vmid; }; if (!matchescomponentid(options.vmid)) { return false; } if (options.name === undefined && options.scope === undefined) { return true; } if (options.scope === undefined) { return this.name === options.name; } if (options.name === undefined) { return this.scope === options.scope; } return options.name === this.name && options.scope === this.scope; }; /** * caches the field id. */ field.prototype._cacheid = function _cacheid (options) { if (this.el && !options.targetof) { this.el._veevalidateid = this.id; } }; /** * updates the field with changed data. */ field.prototype.update = function update (options) { this.targetof = options.targetof || null; this.immediate = options.immediate || this.immediate || false; // update errors scope if the field scope was changed. if (!isnullorundefined(options.scope) && options.scope !== this.scope && iscallable(this.validator.update)) { this.validator.update(this.id, { scope: options.scope }); } this.scope = !isnullorundefined(options.scope) ? options.scope : !isnullorundefined(this.scope) ? this.scope : null; this.name = (!isnullorundefined(options.name) ? string(options.name) : options.name) || this.name || null; this.rules = options.rules !== undefined ? normalizerules(options.rules) : this.rules; this._bails = options.bails !== undefined ? options.bails : this._bails; this.model = options.model || this.model; this.listen = options.listen !== undefined ? options.listen : this.listen; this.classes = (options.classes || this.classes || false) && !this.componentinstance; this.classnames = isobject(options.classnames) ? merge$1(this.classnames, options.classnames) : this.classnames; this.getter = iscallable(options.getter) ? options.getter : this.getter; this._alias = options.alias || this._alias; this.events = (options.events) ? makeeventsarray(options.events) : this.events; this.delay = makedelayobject(this.events, options.delay || this.delay, this._delay); this.updatedependencies(); this.addactionlisteners(); if (!this.name && !this.targetof) { warn('a field is missing a "name" or "data-vv-name" attribute'); } // update required flag flags if (options.rules !== undefined) { this.flags.required = this.isrequired; } // validate if it was validated before and field was updated and there was a rules mutation. if (this.flags.validated && options.rules !== undefined && this.updated) { this.validator.validate(("#" + (this.id))); } this.updated = true; this.addvaluelisteners(); // no need to continue. if (!this.el) { return; } this.updateclasses(); this.updateariaattrs(); }; /** * resets field flags and errors. */ field.prototype.reset = function reset () { var this$1 = this; if (this._cancellationtoken) { this._cancellationtoken.cancelled = true; delete this._cancellationtoken; } var defaults = createflags(); object.keys(this.flags).filter(function (flag) { return flag !== 'required'; }).foreach(function (flag) { this$1.flags[flag] = defaults[flag]; }); this.addactionlisteners(); this.updateclasses(); this.updateariaattrs(); this.updatecustomvalidity(); }; /** * sets the flags and their negated counterparts, and updates the classes and re-adds action listeners. */ field.prototype.setflags = function setflags (flags) { var this$1 = this; var negated = { pristine: 'dirty', dirty: 'pristine', valid: 'invalid', invalid: 'valid', touched: 'untouched', untouched: 'touched' }; object.keys(flags).foreach(function (flag) { this$1.flags[flag] = flags[flag]; // if it has a negation and was not specified, set it as well. if (negated[flag] && flags[negated[flag]] === undefined) { this$1.flags[negated[flag]] = !flags[flag]; } }); if ( flags.untouched !== undefined || flags.touched !== undefined || flags.dirty !== undefined || flags.pristine !== undefined ) { this.addactionlisteners(); } this.updateclasses(); this.updateariaattrs(); this.updatecustomvalidity(); }; /** * determines if the field requires references to target fields. */ field.prototype.updatedependencies = function updatedependencies () { var this$1 = this; // reset dependencies. this.dependencies.foreach(function (d) { return d.field.destroy(); }); this.dependencies = []; // we get the selectors for each field. var fields = object.keys(this.rules).reduce(function (prev, r) { if (validator.istargetrule(r)) { prev.push({ selector: this$1.rules[r][0], name: r }); } return prev; }, []); if (!fields.length || !this.vm || !this.vm.$el) { return; } // must be contained within the same component, so we use the vm root element constrain our dom search. fields.foreach(function (ref$1) { var selector = ref$1.selector; var name = ref$1.name; var ref = this$1.vm.$refs[selector]; var el = array.isarray(ref) ? ref[0] : ref; if (!el) { return; } var options = { vm: this$1.vm, classes: this$1.classes, classnames: this$1.classnames, delay: this$1.delay, scope: this$1.scope, events: this$1.events.join('|'), immediate: this$1.immediate, targetof: this$1.id }; // probably a component. if (iscallable(el.$watch)) { options.component = el; options.el = el.$el; options.getter = resolver.resolvegetter(el.$el, el.$vnode); } else { options.el = el; options.getter = resolver.resolvegetter(el, {}); } this$1.dependencies.push({ name: name, field: new field(options) }); }); }; /** * removes listeners. */ field.prototype.unwatch = function unwatch (tag) { if ( tag === void 0 ) tag = null; if (!tag) { this.watchers.foreach(function (w) { return w.unwatch(); }); this.watchers = []; return; } this.watchers.filter(function (w) { return tag.test(w.tag); }).foreach(function (w) { return w.unwatch(); }); this.watchers = this.watchers.filter(function (w) { return !tag.test(w.tag); }); }; /** * updates the element classes depending on each field flag status. */ field.prototype.updateclasses = function updateclasses () { var this$1 = this; if (!this.classes || this.isdisabled) { return; } var applyclasses = function (el) { toggleclass(el, this$1.classnames.dirty, this$1.flags.dirty); toggleclass(el, this$1.classnames.pristine, this$1.flags.pristine); toggleclass(el, this$1.classnames.touched, this$1.flags.touched); toggleclass(el, this$1.classnames.untouched, this$1.flags.untouched); // make sure we don't set any classes if the state is undetermined. if (!isnullorundefined(this$1.flags.valid) && this$1.flags.validated) { toggleclass(el, this$1.classnames.valid, this$1.flags.valid); } if (!isnullorundefined(this$1.flags.invalid) && this$1.flags.validated) { toggleclass(el, this$1.classnames.invalid, this$1.flags.invalid); } }; if (!ischeckboxorradioinput(this.el)) { applyclasses(this.el); return; } var els = document.queryselectorall(("input[name=\"" + (this.el.name) + "\"]")); toarray(els).foreach(applyclasses); }; /** * adds the listeners required for automatic classes and some flags. */ field.prototype.addactionlisteners = function addactionlisteners () { var this$1 = this; // remove previous listeners. this.unwatch(/class/); if (!this.el) { return; } var onblur = function () { this$1.flags.touched = true; this$1.flags.untouched = false; if (this$1.classes) { toggleclass(this$1.el, this$1.classnames.touched, true); toggleclass(this$1.el, this$1.classnames.untouched, false); } // only needed once. this$1.unwatch(/^class_blur$/); }; var inputevent = istextinput(this.el) ? 'input' : 'change'; var oninput = function () { this$1.flags.dirty = true; this$1.flags.pristine = false; if (this$1.classes) { toggleclass(this$1.el, this$1.classnames.pristine, false); toggleclass(this$1.el, this$1.classnames.dirty, true); } // only needed once. this$1.unwatch(/^class_input$/); }; if (this.componentinstance && iscallable(this.componentinstance.$once)) { this.componentinstance.$once('input', oninput); this.componentinstance.$once('blur', onblur); this.watchers.push({ tag: 'class_input', unwatch: function () { this$1.componentinstance.$off('input', oninput); } }); this.watchers.push({ tag: 'class_blur', unwatch: function () { this$1.componentinstance.$off('blur', onblur); } }); return; } if (!this.el) { return; } addeventlistener(this.el, inputevent, oninput); // checkboxes and radio buttons on mac don't emit blur naturally, so we listen on click instead. var blurevent = ischeckboxorradioinput(this.el) ? 'change' : 'blur'; addeventlistener(this.el, blurevent, onblur); this.watchers.push({ tag: 'class_input', unwatch: function () { this$1.el.removeeventlistener(inputevent, oninput); } }); this.watchers.push({ tag: 'class_blur', unwatch: function () { this$1.el.removeeventlistener(blurevent, onblur); } }); }; field.prototype.checkvaluechanged = function checkvaluechanged () { // handle some people initialize the value to null, since text inputs have empty string value. if (this.initialvalue === null && this.value === '' && istextinput(this.el)) { return false; } return this.value !== this.initialvalue; }; /** * determines the suitable primary event to listen for. */ field.prototype._determineinputevent = function _determineinputevent () { // if its a custom component, use the customized model event or the input event. if (this.componentinstance) { return (this.componentinstance.$options.model && this.componentinstance.$options.model.event) || 'input'; } if (this.model && this.model.lazy) { return 'change'; } if (istextinput(this.el)) { return 'input'; } return 'change'; }; /** * determines the list of events to listen to. */ field.prototype._determineeventlist = function _determineeventlist (defaultinputevent) { // if no event is configured, or it is a component or a text input then respect the user choice. if (!this.events.length || this.componentinstance || istextinput(this.el)) { return [].concat( this.events ); } // force suitable event for non-text type fields. return this.events.map(function (e) { if (e === 'input') { return defaultinputevent; } return e; }); }; /** * adds the listeners required for validation. */ field.prototype.addvaluelisteners = function addvaluelisteners () { var this$1 = this; this.unwatch(/^input_.+/); if (!this.listen || !this.el) { return; } var token = { cancelled: false }; var fn = this.targetof ? function () { this$1.flags.changed = this$1.checkvaluechanged(); this$1.validator.validate(("#" + (this$1.targetof))); } : function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; // if its a dom event, resolve the value, otherwise use the first parameter as the value. if (args.length === 0 || (iscallable(event) && args[0] instanceof event) || (args[0] && args[0].srcelement)) { args[0] = this$1.value; } this$1.flags.changed = this$1.checkvaluechanged(); this$1.validator.validate(("#" + (this$1.id)), args[0]); }; var inputevent = this._determineinputevent(); var events = this._determineeventlist(inputevent); // if there is a model and an on input validation is requested. if (this.model && includes(events, inputevent)) { var ctx = null; var expression = this.model.expression; // if its watchable from the context vm. if (this.model.expression) { ctx = this.vm; expression = this.model.expression; } // watch it from the custom component vm instead. if (!expression && this.componentinstance && this.componentinstance.$options.model) { ctx = this.componentinstance; expression = this.componentinstance.$options.model.prop || 'value'; } if (ctx && expression) { var debouncedfn = debounce(fn, this.delay[inputevent], false, token); var unwatch = ctx.$watch(expression, function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; this$1.flags.pending = true; this$1._cancellationtoken = token; debouncedfn.apply(void 0, args); }); this.watchers.push({ tag: 'input_model', unwatch: unwatch }); // filter out input event as it is already handled by the watcher api. events = events.filter(function (e) { return e !== inputevent; }); } } // add events. events.foreach(function (e) { var debouncedfn = debounce(fn, this$1.delay[e], false, token); var validate = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; this$1.flags.pending = true; this$1._cancellationtoken = token; debouncedfn.apply(void 0, args); }; this$1._addcomponenteventlistener(e, validate); this$1._addhtmleventlistener(e, validate); }); }; field.prototype._addcomponenteventlistener = function _addcomponenteventlistener (evt, validate) { var this$1 = this; if (!this.componentinstance) { return; } this.componentinstance.$on(evt, validate); this.watchers.push({ tag: 'input_vue', unwatch: function () { this$1.componentinstance.$off(evt, validate); } }); }; field.prototype._addhtmleventlistener = function _addhtmleventlistener (evt, validate) { var this$1 = this; if (!this.el || this.componentinstance) { return; } // listen for the current element. var addlistener = function (el) { addeventlistener(el, evt, validate); this$1.watchers.push({ tag: 'input_native', unwatch: function () { el.removeeventlistener(evt, validate); } }); }; addlistener(this.el); if (!ischeckboxorradioinput(this.el)) { return; } var els = document.queryselectorall(("input[name=\"" + (this.el.name) + "\"]")); toarray(els).foreach(function (el) { // skip if it is added by v-validate and is not the current element. if (el._veevalidateid && el !== this$1.el) { return; } addlistener(el); }); }; /** * updates aria attributes on the element. */ field.prototype.updateariaattrs = function updateariaattrs () { var this$1 = this; if (!this.aria || !this.el || !iscallable(this.el.setattribute)) { return; } var applyariaattrs = function (el) { el.setattribute('aria-required', this$1.isrequired ? 'true' : 'false'); el.setattribute('aria-invalid', this$1.flags.invalid ? 'true' : 'false'); }; if (!ischeckboxorradioinput(this.el)) { applyariaattrs(this.el); return; } var els = document.queryselectorall(("input[name=\"" + (this.el.name) + "\"]")); toarray(els).foreach(applyariaattrs); }; /** * updates the custom validity for the field. */ field.prototype.updatecustomvalidity = function updatecustomvalidity () { if (!this.validity || !this.el || !iscallable(this.el.setcustomvalidity) || !this.validator.errors) { return; } this.el.setcustomvalidity(this.flags.valid ? '' : (this.validator.errors.firstbyid(this.id) || '')); }; /** * removes all listeners. */ field.prototype.destroy = function destroy () { // ignore the result of any ongoing validation. if (this._cancellationtoken) { this._cancellationtoken.cancelled = true; } this.unwatch(); this.dependencies.foreach(function (d) { return d.field.destroy(); }); this.dependencies = []; }; object.defineproperties( field.prototype, prototypeaccessors$3 ); // var fieldbag = function fieldbag (items) { if ( items === void 0 ) items = []; this.items = items || []; }; var prototypeaccessors$4 = { length: { configurable: true } }; fieldbag.prototype[typeof symbol === 'function' ? symbol.iterator : '@@iterator'] = function () { var this$1 = this; var index = 0; return { next: function () { return { value: this$1.items[index++], done: index > this$1.items.length }; } }; }; /** * gets the current items length. */ prototypeaccessors$4.length.get = function () { return this.items.length; }; /** * finds the first field that matches the provided matcher object. */ fieldbag.prototype.find = function find$1 (matcher) { return find(this.items, function (item) { return item.matches(matcher); }); }; /** * filters the items down to the matched fields. */ fieldbag.prototype.filter = function filter (matcher) { // multiple matchers to be tried. if (array.isarray(matcher)) { return this.items.filter(function (item) { return matcher.some(function (m) { return item.matches(m); }); }); } return this.items.filter(function (item) { return item.matches(matcher); }); }; /** * maps the field items using the mapping function. */ fieldbag.prototype.map = function map (mapper) { return this.items.map(mapper); }; /** * finds and removes the first field that matches the provided matcher object, returns the removed item. */ fieldbag.prototype.remove = function remove (matcher) { var item = null; if (matcher instanceof field) { item = matcher; } else { item = this.find(matcher); } if (!item) { return null; } var index = this.items.indexof(item); this.items.splice(index, 1); return item; }; /** * adds a field item to the list. */ fieldbag.prototype.push = function push (item) { if (! (item instanceof field)) { throw createerror('fieldbag only accepts instances of field that has an id defined.'); } if (!item.id) { throw createerror('field id must be defined.'); } if (this.find({ id: item.id })) { throw createerror(("field with id " + (item.id) + " is already added.")); } this.items.push(item); }; object.defineproperties( fieldbag.prototype, prototypeaccessors$4 ); var scopedvalidator = function scopedvalidator (base, vm) { this.id = vm._uid; this._base = base; this._paused = false; // create a mirror bag with limited component scope. this.errors = new errorbag(base.errors, this.id); }; var prototypeaccessors$5 = { flags: { configurable: true },rules: { configurable: true },fields: { configurable: true },dictionary: { configurable: true },locale: { configurable: true } }; prototypeaccessors$5.flags.get = function () { var this$1 = this; return this._base.fields.items.filter(function (f) { return f.vmid === this$1.id; }).reduce(function (acc, field) { if (field.scope) { if (!acc[("$" + (field.scope))]) { acc[("$" + (field.scope))] = {}; } acc[("$" + (field.scope))][field.name] = field.flags; } acc[field.name] = field.flags; return acc; }, {}); }; prototypeaccessors$5.rules.get = function () { return this._base.rules; }; prototypeaccessors$5.fields.get = function () { return new fieldbag(this._base.fields.filter({ vmid: this.id })); }; prototypeaccessors$5.dictionary.get = function () { return this._base.dictionary; }; prototypeaccessors$5.locale.get = function () { return this._base.locale; }; prototypeaccessors$5.locale.set = function (val) { this._base.locale = val; }; scopedvalidator.prototype.localize = function localize () { var ref; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return (ref = this._base).localize.apply(ref, args); }; scopedvalidator.prototype.update = function update () { var ref; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return (ref = this._base).update.apply(ref, args); }; scopedvalidator.prototype.attach = function attach (opts) { var attachopts = assign({}, opts, { vmid: this.id }); return this._base.attach(attachopts); }; scopedvalidator.prototype.pause = function pause () { this._paused = true; }; scopedvalidator.prototype.resume = function resume () { this._paused = false; }; scopedvalidator.prototype.remove = function remove (rulename) { return this._base.remove(rulename); }; scopedvalidator.prototype.detach = function detach () { var ref; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return (ref = this._base).detach.apply(ref, args.concat( [this.id] )); }; scopedvalidator.prototype.extend = function extend () { var ref; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return (ref = this._base).extend.apply(ref, args); }; scopedvalidator.prototype.validate = function validate (descriptor, value, opts) { if ( opts === void 0 ) opts = {}; if (this._paused) { return promise.resolve(true); } return this._base.validate(descriptor, value, assign({}, { vmid: this.id }, opts || {})); }; scopedvalidator.prototype.validateall = function validateall (values$$1, opts) { if ( opts === void 0 ) opts = {}; if (this._paused) { return promise.resolve(true); } return this._base.validateall(values$$1, assign({}, { vmid: this.id }, opts || {})); }; scopedvalidator.prototype.validatescopes = function validatescopes (opts) { if ( opts === void 0 ) opts = {}; if (this._paused) { return promise.resolve(true); } return this._base.validatescopes(assign({}, { vmid: this.id }, opts || {})); }; scopedvalidator.prototype.destroy = function destroy () { delete this.id; delete this._base; }; scopedvalidator.prototype.reset = function reset (matcher) { return this._base.reset(object.assign({}, matcher || {}, { vmid: this.id })); }; scopedvalidator.prototype.flag = function flag () { var ref; var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return (ref = this._base).flag.apply(ref, args.concat( [this.id] )); }; object.defineproperties( scopedvalidator.prototype, prototypeaccessors$5 ); // /** * checks if a parent validator instance was requested. */ var requestsvalidator = function (injections) { if (isobject(injections) && injections.$validator) { return true; } return false; }; var mixin = { provide: function provide () { if (this.$validator && !isbuiltincomponent(this.$vnode)) { return { $validator: this.$validator }; } return {}; }, beforecreate: function beforecreate () { // if built in do nothing. if (isbuiltincomponent(this.$vnode)) { return; } // if its a root instance set the config if it exists. if (!this.$parent) { config.merge(this.$options.$_veevalidate || {}); } var options = config.resolve(this); // if its a root instance, inject anyways, or if it requested a new instance. if (!this.$parent || (this.$options.$_veevalidate && /new/.test(this.$options.$_veevalidate.validator))) { this.$validator = new scopedvalidator(config.dependency('validator'), this); } var requested = requestsvalidator(this.$options.inject); // if automatic injection is enabled and no instance was requested. if (! this.$validator && options.inject && !requested) { this.$validator = new scopedvalidator(config.dependency('validator'), this); } // don't inject errors or fieldbag as no validator was resolved. if (! requested && ! this.$validator) { return; } // there is a validator but it isn't injected, mark as reactive. if (!requested && this.$validator) { var vue = this.$options._base; // the vue constructor. vue.util.definereactive(this.$validator, 'errors', this.$validator.errors); } if (! this.$options.computed) { this.$options.computed = {}; } this.$options.computed[options.errorbagname || 'errors'] = function errorbaggetter () { return this.$validator.errors; }; this.$options.computed[options.fieldsbagname || 'fields'] = function fieldbaggetter () { return this.$validator.fields.items.reduce(function (acc, field) { if (field.scope) { if (!acc[("$" + (field.scope))]) { acc[("$" + (field.scope))] = {}; } acc[("$" + (field.scope))][field.name] = field.flags; return acc; } acc[field.name] = field.flags; return acc; }, {}); }; }, beforedestroy: function beforedestroy () { if (this.$validator && this._uid === this.$validator.id) { this.$validator.errors.clear(); // remove errors generated by this component. } } }; // /** * finds the requested field by id from the context object. */ function findfield (el, context) { if (!context || !context.$validator) { return null; } return context.$validator.fields.find({ id: el._veevalidateid }); } var directive = { bind: function bind (el, binding, vnode) { var validator = vnode.context.$validator; if (!validator) { { warn("no validator instance is present on vm, did you forget to inject '$validator'?"); } return; } var fieldoptions = resolver.generate(el, binding, vnode); validator.attach(fieldoptions); }, inserted: function inserted (el, binding, vnode) { var field = findfield(el, vnode.context); var scope = resolver.resolvescope(el, binding, vnode); // skip if scope hasn't changed. if (!field || scope === field.scope) { return; } // only update scope. field.update({ scope: scope }); // allows the field to re-evaluated once more in the update hook. field.updated = false; }, update: function update (el, binding, vnode) { var field = findfield(el, vnode.context); // make sure we don't do unneccasary work if no important change was done. if (!field || (field.updated && isequal$1(binding.value, binding.oldvalue))) { return; } var scope = resolver.resolvescope(el, binding, vnode); var rules = resolver.resolverules(el, binding, vnode); field.update({ scope: scope, rules: rules }); }, unbind: function unbind (el, binding, ref) { var context = ref.context; var field = findfield(el, context); if (!field) { return; } context.$validator.detach(field); } }; var vue; function install (_vue, options) { if ( options === void 0 ) options = {}; if (vue && _vue === vue) { { warn('already installed, vue.use(veevalidate) should only be called once.'); } return; } detectpassivesupport(); vue = _vue; var validator = new validator(null, options); var localvue = new vue({ data: function () { return ({ errors: validator.errors, fields: validator.fields }); } }); config.register('vm', localvue); config.register('validator', validator); config.merge(options); var ref = config.current; var dictionary = ref.dictionary; var i18n = ref.i18n; if (dictionary) { validator.localize(dictionary); // merge the dictionary. } var onlocalechanged = function () { validator.errors.regenerate(); }; // watch locale changes using localvue instance or i18n. if (!i18n) { if (typeof window !== 'undefined') { localvue.$on('localechanged', onlocalechanged); } } else { i18n._vm.$watch('locale', onlocalechanged); } if (!i18n && options.locale) { validator.localize(options.locale); // set the locale } validator.setstrictmode(config.current.strict); vue.mixin(mixin); vue.directive('validate', directive); } // function use (plugin, options) { if ( options === void 0 ) options = {}; if (!iscallable(plugin)) { return warn('the plugin must be a callable function'); } plugin({ validator: validator, errorbag: errorbag, rules: validator.rules }, options); } // var normalize = function (fields) { if (array.isarray(fields)) { return fields.reduce(function (prev, curr) { if (includes(curr, '.')) { prev[curr.split('.')[1]] = curr; } else { prev[curr] = curr; } return prev; }, {}); } return fields; }; // combines two flags using either and or or depending on the flag type. var combine = function (lhs, rhs) { var mapper = { pristine: function (lhs, rhs) { return lhs && rhs; }, dirty: function (lhs, rhs) { return lhs || rhs; }, touched: function (lhs, rhs) { return lhs || rhs; }, untouched: function (lhs, rhs) { return lhs && rhs; }, valid: function (lhs, rhs) { return lhs && rhs; }, invalid: function (lhs, rhs) { return lhs || rhs; }, pending: function (lhs, rhs) { return lhs || rhs; }, required: function (lhs, rhs) { return lhs || rhs; }, validated: function (lhs, rhs) { return lhs && rhs; } }; return object.keys(mapper).reduce(function (flags, flag) { flags[flag] = mapper[flag](lhs[flag], rhs[flag]); return flags; }, {}); }; var mapscope = function (scope, deep) { if ( deep === void 0 ) deep = true; return object.keys(scope).reduce(function (flags, field) { if (!flags) { flags = assign({}, scope[field]); return flags; } // scope. var isscope = field.indexof('$') === 0; if (deep && isscope) { return combine(mapscope(scope[field]), flags); } else if (!deep && isscope) { return flags; } flags = combine(flags, scope[field]); return flags; }, null); }; /** * maps fields to computed functions. */ var mapfields = function (fields) { if (!fields) { return function () { return mapscope(this.$validator.flags); }; } var normalized = normalize(fields); return object.keys(normalized).reduce(function (prev, curr) { var field = normalized[curr]; prev[curr] = function mappedfield () { // if field exists if (this.$validator.flags[field]) { return this.$validator.flags[field]; } // scopeless fields were selected. if (normalized[curr] === '*') { return mapscope(this.$validator.flags, false); } // if it has a scope defined var index = field.indexof('.'); if (index <= 0) { return {}; } var ref = field.split('.'); var scope = ref[0]; var name = ref.slice(1); scope = this.$validator.flags[("$" + scope)]; name = name.join('.'); // an entire scope was selected: scope.* if (name === '*' && scope) { return mapscope(scope); } if (scope && scope[name]) { return scope[name]; } return {}; }; return prev; }, {}); }; var errorcomponent = { name: 'vv-error', inject: ['$validator'], functional: true, props: { for: { type: string, required: true }, tag: { type: string, default: 'span' } }, render: function render (createelement, ref) { var props = ref.props; var injections = ref.injections; return createelement(props.tag, injections.$validator.errors.first(props.for)); } }; var minimal = { install: install, use: use, directive: directive, mixin: mixin, mapfields: mapfields, validator: validator, errorbag: errorbag, errorcomponent: errorcomponent, version: '2.1.0-beta.9' }; // rules plugin definition. var rulesplugin = function (ref) { var validator = ref.validator; object.keys(rules).foreach(function (rule) { validator.extend(rule, rules[rule].validate, assign({}, rules[rule].options, { paramnames: rules[rule].paramnames })); }); // merge the english messages. validator.localize('en', locale$1); }; // install the rules via the plugin api. minimal.use(rulesplugin); minimal.rules = rules; return minimal; })));