index.js 923 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { getCurrentInstance, onMounted } from 'vue'
  2. import Schema from 'async-validator'
  3. export default (rules = {}, formRef = 'formRef', messageRef = 'messageRef') => {
  4. let refs = {}
  5. let validator = new Schema(rules)
  6. onMounted(() => {
  7. refs = getCurrentInstance().refs
  8. })
  9. return {
  10. setRules(rules) {
  11. validator = new Schema(rules)
  12. },
  13. validate(data = refs[formRef] && refs[formRef].model) {
  14. if (data) {
  15. return new Promise((resolve, reject) => {
  16. validator.validate(data).then(() => {
  17. resolve()
  18. }).catch(({ errors, fields }) => {
  19. if (refs[formRef].errorType === 'message') {
  20. refs[messageRef].error(errors[0].message)
  21. } else{
  22. uni.showToast({
  23. icon: 'none',
  24. title: errors[0].message
  25. })
  26. }
  27. reject(errors, fields)
  28. })
  29. })
  30. } else{
  31. return Promise.reject('请确认form是否加了ref、model属性')
  32. }
  33. }
  34. }
  35. }