| | |
| | | */ |
| | | |
| | | <template> |
| | | <view class="c-form-item"> |
| | | <view |
| | | class="c-form-item" |
| | | ref="formItem" |
| | | > |
| | | <slot :itemRes="itemRes" /> |
| | | </view> |
| | | </template> |
| | | |
| | | <script> |
| | | import Schema from 'async-validator'; |
| | | import { $ } from '@tarojs/extend'; |
| | | import { validateMsgs } from './validateMsgs.js'; |
| | | |
| | | export default { |
| | |
| | | mounted() { |
| | | this.$nextTick(() => { |
| | | // 注册验证 |
| | | this.formRes.$regItemValidator(this.name, validateType => { |
| | | this.formRes.$regItemValidator(this.name, (validateType, errMsg) => { |
| | | // 直接设定错误 |
| | | if (validateType === 'setError') { |
| | | this.$setError(); |
| | | return new Promise((resolve, reject) => { |
| | | $(this.$refs.formItem) |
| | | .offset() |
| | | .then(offset => { |
| | | resolve({ |
| | | name: this.name, |
| | | passed: false, |
| | | msg: errMsg, |
| | | offset, |
| | | }); |
| | | }); |
| | | }); |
| | | } |
| | | // 未设置验证 |
| | | if (!this.required && !this.rules) { |
| | | else if (!this.required && !this.rules) { |
| | | this.error = false; |
| | | return Promise.resolve({ |
| | | name: this.name, |
| | | passed: true, |
| | | }); |
| | | } else { |
| | | } |
| | | // 正常验证 |
| | | else { |
| | | // 验证规则 |
| | | const descriptor = this.rules || []; |
| | | if (this.required) { |
| | |
| | | }); |
| | | // 汉化通用验证消息 |
| | | validator.messages(validateMsgs); |
| | | return validator |
| | | .validate({ |
| | | [this.name]: this.formRes.formData[this.name], |
| | | }) |
| | | .then( |
| | | res => { |
| | | this.error = false; |
| | | return { |
| | | name: this.name, |
| | | passed: true, |
| | | }; |
| | | }, |
| | | ({ errors, fields }) => { |
| | | if (validateType !== 'msgOnly') { |
| | | this.error = true; |
| | | clearTimeout(this.errTimer); |
| | | this.errTimer = setTimeout(() => { |
| | | this.error = false; |
| | | }, 5000); |
| | | return new Promise((resolve, reject) => { |
| | | validator |
| | | .validate({ |
| | | [this.name]: this.formRes.formData[this.name], |
| | | }) |
| | | .then( |
| | | res => { |
| | | this.error = false; |
| | | resolve({ |
| | | name: this.name, |
| | | passed: true, |
| | | }); |
| | | }, |
| | | ({ errors, fields }) => { |
| | | if (validateType !== 'msgOnly') { |
| | | this.$setError(); |
| | | } |
| | | $(this.$refs.formItem) |
| | | .offset() |
| | | .then(offset => { |
| | | resolve({ |
| | | name: this.name, |
| | | passed: false, |
| | | msg: errors[0].message.replace( |
| | | this.name, |
| | | this.label || this.name |
| | | ), |
| | | offset, |
| | | }); |
| | | }); |
| | | } |
| | | return { |
| | | name: this.name, |
| | | passed: false, |
| | | msg: errors[0].message.replace( |
| | | this.name, |
| | | this.label || this.name |
| | | ), |
| | | }; |
| | | } |
| | | ); |
| | | ); |
| | | }); |
| | | } |
| | | }); |
| | | }); |