rules.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import Schema from '../common/async-validator/index';
  2. /**
  3. * @param tipType String [toast , message , text]
  4. */
  5. module.exports = Behavior({
  6. behaviors: [],
  7. properties: {
  8. // 校验
  9. rules: {
  10. type: Object,
  11. },
  12. tipType: {
  13. type: String,
  14. value: ''
  15. }
  16. },
  17. data: {
  18. schema: '',
  19. tipFun: {
  20. 'message': 'showMessage',
  21. 'toast': 'showToast',
  22. },
  23. tipContent: {
  24. 'message': 'content',
  25. 'toast': 'title',
  26. },
  27. errorText: '',
  28. },
  29. methods: {
  30. initRules() {
  31. const rulesName = this.data.name;
  32. const {
  33. rules
  34. } = this.data;
  35. if (!rules) return;
  36. const schema = new Schema({
  37. [rulesName]: this.data.rules,
  38. });
  39. this.setData({
  40. schema,
  41. });
  42. },
  43. validatorData({
  44. value
  45. }) {
  46. const {
  47. rules,
  48. tipType,
  49. tipFun,
  50. tipContent
  51. } = this.data;
  52. if (!rules) return;
  53. const validateValue = {
  54. [this.data.name]: value
  55. };
  56. this.data.schema.validate(validateValue, (errors, fields) => {
  57. this.triggerEvent('linvalidate', {
  58. errors,
  59. isError: !!errors
  60. });
  61. if (errors && tipType) {
  62. const funName = tipFun[tipType];
  63. const contentName = tipContent[tipType];
  64. if (tipType === 'text') {
  65. this.setData({
  66. errorText: errors[0].message
  67. });
  68. return;
  69. }
  70. if (!wx.lin || !wx.lin[funName]) {
  71. wx.showToast({
  72. icon: 'none',
  73. title: `请在页面内引入${tipType}组件`
  74. })
  75. return;
  76. }
  77. wx.lin[funName] && wx.lin[funName]({
  78. [contentName]: errors[0].message,
  79. duration: 1500,
  80. mask: false,
  81. });
  82. } else if (!errors && tipType) {
  83. this.setData({
  84. errorText: ''
  85. });
  86. }
  87. });
  88. }
  89. }
  90. })