rules.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { createAddAPI } from '../util'
  2. import { types } from './types'
  3. const rules = {
  4. required: (val, required, type) => {
  5. type = type || (Array.isArray(val) ? 'array' : typeof val)
  6. if (type === 'array' && Array.isArray(val)) {
  7. return val.length > 0
  8. }
  9. return val !== '' && val !== undefined && val !== null
  10. },
  11. type: (val, type) => {
  12. return !types[type] || types[type](val)
  13. },
  14. min: (val, min, type) => {
  15. type = type || (typeof val)
  16. if (type === 'number' || type === 'date') {
  17. return Number(val) >= min
  18. } else {
  19. return val.length >= min
  20. }
  21. },
  22. max: (val, max, type) => {
  23. type = type || (typeof val)
  24. if (type === 'number' || type === 'date') {
  25. return Number(val) <= max
  26. } else {
  27. return val.length <= max
  28. }
  29. },
  30. len: (val, len, type) => {
  31. type = type || (typeof val)
  32. let target = val
  33. if (target.length === undefined) {
  34. target = type === 'object' ? Object.keys(target) : String(target)
  35. }
  36. return target.length === len
  37. },
  38. notWhitespace: (val, config, type) => {
  39. return !/^\s+$/.test(val)
  40. },
  41. pattern: (val, pattern, type) => {
  42. return pattern.test(val)
  43. },
  44. custom: (val, custom, type) => {
  45. return custom(val)
  46. }
  47. }
  48. const addRule = createAddAPI(rules)
  49. export { rules, addRule }