rules.js 2.0 KB

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