validate.js 971 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export default (form, rules) => {
  2. return new Promise((resolve, reject) => {
  3. if (form && rules) {
  4. let pass = true
  5. a: for (let key in rules) {
  6. let rule = rules[key]
  7. if (Array.isArray(rule)) {
  8. for (let i = 0; i < rule.length; i++) {
  9. const result = validate(rule[i], form[key])
  10. if (!result) {
  11. pass = false
  12. break a
  13. }
  14. }
  15. } else {
  16. const result = validate(rule, form[key])
  17. if (!result) {
  18. pass = false
  19. break a
  20. }
  21. }
  22. }
  23. if (pass) resolve()
  24. else reject()
  25. } else {
  26. reject('需校验的对象为空')
  27. }
  28. })
  29. }
  30. const validate = (rule, value) => {
  31. let pass = true
  32. if (rule && rule.pattern && !rule.pattern.test(value)) {
  33. uni.showToast({
  34. title: rule.message || '校验失败',
  35. icon: 'none'
  36. })
  37. pass = false
  38. } else if (rule && rule.required && !value) {
  39. uni.showToast({
  40. title: rule.message || '校验失败',
  41. icon: 'none'
  42. })
  43. pass = false
  44. }
  45. return pass
  46. }