WxValidate.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /**
  2. * 表单验证
  3. *
  4. * @param {Object} rules 验证字段的规则
  5. * @param {Object} messages 验证字段的提示信息
  6. *
  7. */
  8. class WxValidate {
  9. constructor(rules = {}, messages = {}) {
  10. Object.assign(this, {
  11. rules,
  12. messages,
  13. })
  14. this.__init()
  15. }
  16. /**
  17. * __init
  18. */
  19. __init() {
  20. this.__initMethods()
  21. this.__initDefaults()
  22. this.__initData()
  23. }
  24. /**
  25. * 初始化数据
  26. */
  27. __initData() {
  28. this.form = {}
  29. this.errorList = []
  30. }
  31. /**
  32. * 初始化默认提示信息
  33. */
  34. __initDefaults() {
  35. this.defaults = {
  36. messages: {
  37. required: '这是必填字段。',
  38. email: '请输入有效的电子邮件地址。',
  39. tel: '请输入11位的手机号码。',
  40. url: '请输入有效的网址。',
  41. date: '请输入有效的日期。',
  42. dateISO: '请输入有效的日期(ISO),例如:2009-06-23,1998/01/22。',
  43. number: '请输入有效的数字。',
  44. digits: '只能输入数字。',
  45. idcard: '请输入18位的有效身份证。',
  46. equalTo: this.formatTpl('输入值必须和 {0} 相同。'),
  47. contains: this.formatTpl('输入值必须包含 {0}。'),
  48. minlength: this.formatTpl('最少要输入 {0} 个字符。'),
  49. maxlength: this.formatTpl('最多可以输入 {0} 个字符。'),
  50. rangelength: this.formatTpl('请输入长度在 {0} 到 {1} 之间的字符。'),
  51. min: this.formatTpl('请输入不小于 {0} 的数值。'),
  52. max: this.formatTpl('请输入不大于 {0} 的数值。'),
  53. range: this.formatTpl('请输入范围在 {0} 到 {1} 之间的数值。'),
  54. }
  55. }
  56. }
  57. /**
  58. * 初始化默认验证方法
  59. */
  60. __initMethods() {
  61. const that = this
  62. that.methods = {
  63. /**
  64. * 验证必填元素
  65. */
  66. required(value, param) {
  67. if (!that.depend(param)) {
  68. return 'dependency-mismatch'
  69. } else if (typeof value === 'number') {
  70. value = value.toString()
  71. } else if (typeof value === 'boolean') {
  72. return !0
  73. }
  74. return value.length > 0
  75. },
  76. /**
  77. * 验证电子邮箱格式
  78. */
  79. email(value) {
  80. return that.optional(value) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value)
  81. },
  82. /**
  83. * 验证手机格式
  84. */
  85. tel(value) {
  86. return that.optional(value) || /^1[34578]\d{9}$/.test(value)
  87. },
  88. /**
  89. * 验证URL格式
  90. */
  91. url(value) {
  92. return that.optional(value) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value)
  93. },
  94. /**
  95. * 验证日期格式
  96. */
  97. date(value) {
  98. return that.optional(value) || !/Invalid|NaN/.test(new Date(value).toString())
  99. },
  100. /**
  101. * 验证ISO类型的日期格式
  102. */
  103. dateISO(value) {
  104. return that.optional(value) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
  105. },
  106. /**
  107. * 验证十进制数字
  108. */
  109. number(value) {
  110. return that.optional(value) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)
  111. },
  112. /**
  113. * 验证整数
  114. */
  115. digits(value) {
  116. return that.optional(value) || /^\d+$/.test(value)
  117. },
  118. /**
  119. * 验证身份证号码
  120. */
  121. idcard(value) {
  122. return that.optional(value) || /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)
  123. },
  124. /**
  125. * 验证两个输入框的内容是否相同
  126. */
  127. equalTo(value, param) {
  128. return that.optional(value) || value === that.scope.detail.value[param]
  129. },
  130. /**
  131. * 验证是否包含某个值
  132. */
  133. contains(value, param) {
  134. return that.optional(value) || value.indexOf(param) >= 0
  135. },
  136. /**
  137. * 验证最小长度
  138. */
  139. minlength(value, param) {
  140. return that.optional(value) || value.length >= param
  141. },
  142. /**
  143. * 验证最大长度
  144. */
  145. maxlength(value, param) {
  146. return that.optional(value) || value.length <= param
  147. },
  148. /**
  149. * 验证一个长度范围[min, max]
  150. */
  151. rangelength(value, param) {
  152. return that.optional(value) || (value.length >= param[0] && value.length <= param[1])
  153. },
  154. /**
  155. * 验证最小值
  156. */
  157. min(value, param) {
  158. return that.optional(value) || value >= param
  159. },
  160. /**
  161. * 验证最大值
  162. */
  163. max(value, param) {
  164. return that.optional(value) || value <= param
  165. },
  166. /**
  167. * 验证一个值范围[min, max]
  168. */
  169. range(value, param) {
  170. return that.optional(value) || (value >= param[0] && value <= param[1])
  171. },
  172. }
  173. }
  174. /**
  175. * 添加自定义验证方法
  176. * @param {String} name 方法名
  177. * @param {Function} method 函数体,接收两个参数(value, param),value表示元素的值,param表示参数
  178. * @param {String} message 提示信息
  179. */
  180. addMethod(name, method, message) {
  181. this.methods[name] = method
  182. this.defaults.messages[name] = message !== undefined ? message : this.defaults.messages[name]
  183. }
  184. /**
  185. * 判断验证方法是否存在
  186. */
  187. isValidMethod(value) {
  188. let methods = []
  189. for(let method in this.methods) {
  190. if (method && typeof this.methods[method] === 'function') {
  191. methods.push(method)
  192. }
  193. }
  194. return methods.indexOf(value) !== -1
  195. }
  196. /**
  197. * 格式化提示信息模板
  198. */
  199. formatTpl(source, params) {
  200. const that = this
  201. if (arguments.length === 1) {
  202. return function() {
  203. let args = Array.from(arguments)
  204. args.unshift(source)
  205. return that.formatTpl.apply(this, args)
  206. }
  207. }
  208. if (params === undefined) {
  209. return source
  210. }
  211. if (arguments.length > 2 && params.constructor !== Array) {
  212. params = Array.from(arguments).slice(1)
  213. }
  214. if (params.constructor !== Array) {
  215. params = [ params ]
  216. }
  217. params.forEach(function(n, i) {
  218. source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function() {
  219. return n
  220. })
  221. })
  222. return source
  223. }
  224. /**
  225. * 判断规则依赖是否存在
  226. */
  227. depend(param) {
  228. switch(typeof param) {
  229. case 'boolean':
  230. param = param
  231. break
  232. case 'string':
  233. param = !!param.length
  234. break
  235. case 'function':
  236. param = param()
  237. default:
  238. param = !0
  239. }
  240. return param
  241. }
  242. /**
  243. * 判断输入值是否为空
  244. */
  245. optional(value) {
  246. return !this.methods.required(value) && 'dependency-mismatch'
  247. }
  248. /**
  249. * 获取自定义字段的提示信息
  250. * @param {String} param 字段名
  251. * @param {Object} rule 规则
  252. */
  253. customMessage(param, rule) {
  254. const params = this.messages[param]
  255. const isObject = typeof params === 'object'
  256. if (params && isObject) return params[rule.method]
  257. }
  258. /**
  259. * 获取某个指定字段的提示信息
  260. * @param {String} param 字段名
  261. * @param {Object} rule 规则
  262. */
  263. defaultMessage(param, rule) {
  264. let message = this.customMessage(param, rule) || this.defaults.messages[rule.method]
  265. let type = typeof message
  266. if (type === 'undefined') {
  267. message = `Warning: No message defined for ${rule.method}.`
  268. } else if (type === 'function') {
  269. message = message.call(this, rule.parameters)
  270. }
  271. return message
  272. }
  273. /**
  274. * 缓存错误信息
  275. * @param {String} param 字段名
  276. * @param {Object} rule 规则
  277. * @param {String} value 元素的值
  278. */
  279. formatTplAndAdd(param, rule, value) {
  280. let msg = this.defaultMessage(param, rule)
  281. this.errorList.push({
  282. param: param,
  283. msg: msg,
  284. value: value,
  285. })
  286. }
  287. /**
  288. * 验证某个指定字段的规则
  289. * @param {String} param 字段名
  290. * @param {Object} rules 规则
  291. * @param {Object} event 表单数据对象
  292. */
  293. checkParam(param, rules, event) {
  294. // 缓存表单数据对象
  295. this.scope = event
  296. // 缓存字段对应的值
  297. const data = event.detail.value
  298. const value = data[param] || ''
  299. // 遍历某个指定字段的所有规则,依次验证规则,否则缓存错误信息
  300. for(let method in rules) {
  301. // 判断验证方法是否存在
  302. if (this.isValidMethod(method)) {
  303. // 缓存规则的属性及值
  304. const rule = {
  305. method: method,
  306. parameters: rules[method]
  307. }
  308. // 调用验证方法
  309. const result = this.methods[method](value, rule.parameters)
  310. // 若result返回值为dependency-mismatch,则说明该字段的值为空或非必填字段
  311. if (result === 'dependency-mismatch') {
  312. continue
  313. }
  314. this.setValue(param, method, result, value)
  315. // 判断是否通过验证,否则缓存错误信息,跳出循环
  316. if (!result) {
  317. this.formatTplAndAdd(param, rule, value)
  318. break
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * 设置字段的默认验证值
  325. * @param {String} param 字段名
  326. */
  327. setView(param) {
  328. this.form[param] = {
  329. $name: param,
  330. $valid: true,
  331. $invalid: false,
  332. $error: {},
  333. $success: {},
  334. $viewValue: ``,
  335. }
  336. }
  337. /**
  338. * 设置字段的验证值
  339. * @param {String} param 字段名
  340. * @param {String} method 字段的方法
  341. * @param {Boolean} result 是否通过验证
  342. * @param {String} value 字段的值
  343. */
  344. setValue(param, method, result, value) {
  345. const params = this.form[param]
  346. params.$valid = result
  347. params.$invalid = !result
  348. params.$error[method] = !result
  349. params.$success[method] = result
  350. params.$viewValue = value
  351. }
  352. /**
  353. * 验证所有字段的规则,返回验证是否通过
  354. * @param {Object} event 表单数据对象
  355. */
  356. checkForm(event) {
  357. this.__initData()
  358. for (let param in this.rules) {
  359. this.setView(param)
  360. this.checkParam(param, this.rules[param], event)
  361. }
  362. return this.valid()
  363. }
  364. /**
  365. * 返回验证是否通过
  366. */
  367. valid() {
  368. return this.size() === 0
  369. }
  370. /**
  371. * 返回错误信息的个数
  372. */
  373. size() {
  374. return this.errorList.length
  375. }
  376. /**
  377. * 返回所有错误信息
  378. */
  379. validationErrors() {
  380. return this.errorList
  381. }
  382. }
  383. export default WxValidate