Newer
Older
KaiFengPC / src / utils / validate-helper.js
@zhangdeliang zhangdeliang on 23 May 2 KB 初始化项目
  1. export function required(fieldName = '', option = {}) {
  2. const defaultOpt = {
  3. required: true,
  4. message: `${fieldName}不能为空`,
  5. trigger: ['change', 'blur']
  6. }
  7.  
  8. return {
  9. ...defaultOpt,
  10. ...option
  11. }
  12. }
  13.  
  14. export function isInteger(fieldName = '', option = {}) {
  15. const IntegerRegex = /^\d+$/
  16. const defaultOpt = {
  17. trigger: ['change', 'blur'],
  18. validator: (rule, value, cb) => {
  19. if (value) {
  20. if (IntegerRegex.test(value)) {
  21. const max = option?.max
  22. const min = option?.min
  23. if (max && value * 1 > max) {
  24. cb(new Error(`${fieldName}不能大于${max}`))
  25. } else if((min || min === 0) && value * 1 < min) {
  26. cb(new Error(`${fieldName}不能小于${min}`))
  27. } else {
  28. cb()
  29. }
  30. } else {
  31. cb(new Error(`${fieldName}不正确`))
  32. }
  33. } else {
  34. option.required ? cb(new Error(`${fieldName}不能为空`)) : cb()
  35. }
  36. }
  37. }
  38.  
  39. return {
  40. ...defaultOpt,
  41. ...option
  42. }
  43. }
  44.  
  45. export const isNumber = (fieldName = '', option = {}) => {
  46. const numberRegex = /^(-?\d+)(\.\d+)?$/
  47. const defaultOpt = {
  48. trigger: ['change', 'blur'],
  49. validator: (rule, value, cb) => {
  50. if (value) {
  51. if (numberRegex.test(value)) {
  52. const max = option?.max
  53. const min = option?.min
  54. if (max && value * 1 > max) {
  55. cb(new Error(`${fieldName}不能大于${max}`))
  56. } else if((min || min === 0) && value * 1 < min) {
  57. cb(new Error(`${fieldName}不能小于${min}`))
  58. } else {
  59. cb()
  60. }
  61. } else {
  62. cb(new Error(`${fieldName}不正确`))
  63. }
  64. } else {
  65. option.required ? cb(new Error(`${fieldName}不能为空`)) : cb()
  66. }
  67. }
  68. }
  69.  
  70. return {
  71. ...defaultOpt,
  72. ...option
  73. }
  74. }
  75.  
  76. export const isScope = (fieldName = '', option = {}) => {
  77. const numberRegex = /^(-?\d+)(\.\d+)?$/
  78. const defaultOpt = {
  79. trigger: ['change', 'blur'],
  80. validator: (rule, value, cb) => {
  81. if (value) {
  82. if(numberRegex.test(value)){
  83. const data = option?.data?.value || option?.data || null
  84. if(!data) cb(new Error('校验异常'))
  85. const props = rule.field.split('.')
  86. const { downValue, upValue } = data[props[0]][props[1]]
  87. if(parseFloat(value) >= downValue * 1 && parseFloat(value) <= upValue * 1){
  88. cb()
  89. } else {
  90. cb(new Error('请输入参考值范围的值'))
  91. }
  92. } else {
  93. cb(new Error('请输入参考值范围的值'))
  94. }
  95. } else {
  96. option.required ? cb(new Error(`${fieldName}不能为空`)) : cb()
  97. }
  98. }
  99. }
  100.  
  101. return {
  102. ...defaultOpt,
  103. ...option
  104. }
  105. }