x-validator
Version:
params validator
3 lines (2 loc) • 2.68 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).Validator={})}(this,(function(e){"use strict";var t=/^\d{4}\-\d{2}\-\d{2}$/,r=/^\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}$/;function n(e){return Object.prototype.toString.call(e).toLowerCase().slice(8,-1)}function i(e,t){for(var r in t)e[r]=t[r]}function a(e,t){return"number"!==n(t)||t%1!=0?"type":e.hasOwnProperty("min")&&t<e.min?"min":e.hasOwnProperty("max")&&t>e.max?"max":void 0}function o(e,t){return"number"!==n(t)||isNaN(t)?"type":e.hasOwnProperty("min")&&t<e.min?"min":e.hasOwnProperty("max")&&t>e.max?"max":void 0}function s(e,t){if("string"!==n(t))return"type";if(""===t)return!0===e.empty?void 0:"empty";if(e.hasOwnProperty("min")&&t.length<e.min)return"min";if(e.hasOwnProperty("max")&&t.length>e.max)return"max";if(e.hasOwnProperty("pattern")&&!e.pattern.test(t))return"pattern";if(e.hasOwnProperty("custom")){var r=e.custom(t);if(r)return r}}function u(e,t){return"boolean"!==n(t)?"type":e.hasOwnProperty("value")&&e.value!==t?"value":void 0}function c(e,t){if(e.values.indexOf(t)<0)return"type"}function p(e,t){if(!t||"array"!==n(t))return"type";var r=t.length;if(e.hasOwnProperty("min")&&r<e.min)return"min";if(e.hasOwnProperty("max")&&r>e.max)return"max";var i=e.itemType;if(i)for(var a=0;a<r;a++)if(n(t[a])!==i)return"itemType"}function f(e,t){if(!t||"object"!==n(t))return"type"}function m(e,r){var n={type:"string",pattern:t},a={};return i(a,e),i(a,n),s(a,r)}function y(e,t){var n={type:"string",pattern:r},a={};return i(a,e),i(a,n),s(a,t)}var h=function(){this.rules={int:a,integer:a,number:o,string:s,bool:u,boolean:u,enum:c,array:p,object:f,date:m,dateTime:y},this.messages={}};h.prototype.add=function(e,t,r){"object"===n(e)?(i(this.rules,e),"object"===n(t)&&i(this.messages,t)):(this.rules[e]=t,this.messages[e]=r)},h.prototype.validate=function(e,t,r){var i={};for(var a in t){var o=t[a];switch(n(o)){case"string":o={type:o};break;case"array":o={type:"enum",values:o};break;case"regexp":o={type:"string",pattern:o}}if("object"!==n(o)||!o.type)throw new Error(a+"'s rule is not found.");var s=void 0;if(e.hasOwnProperty(a))s=this.rules[o.type](o,e[a],e);else{if(!1===o.required)continue;s="required"}if(s){var u=r&&r[a]&&r[a][s];"string"!==n(u)&&(u=this.messages[o.type]&&this.messages[o.type][s]),i[a]="string"===n(u)?u:s}}if(Object.keys(i).length>0)return i},e.Validator=h,e.checkArray=p,e.checkBoolean=u,e.checkDate=m,e.checkDateTime=y,e.checkEnum=c,e.checkInteger=a,e.checkNumber=o,e.checkObject=f,e.checkString=s,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=index.min.js.map