如何使用 Vuelidate 异步规则
How to use a Vuelidate async rule
我正在尝试向 Vue 中的表单添加自定义异步验证并遵循 documented example,但验证永远不会失败。这是我的代码:
<script>
import { reactive } from 'vue';
import useVuelidate from '@vuelidate/core';
import { required, email } from '@vuelidate/validators';
export default {
template:
'<input v-model="state.postcode" /><div v-if="v$.postcode.$silentErrors.length">never shows</div>',
setup() {
const state = reactive({
postcode: 'OX14 8JW',
});
const rules = {
postcode: {
async startsWithX(value) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const isOk = value && value[0] === 'X';
// console.log('sanity check: ', isOk);
return Boolean(isOk);
},
},
};
const v$ = useVuelidate(rules, state);
return { v$, state };
},
};
</script>
谁能帮我让这个异步验证工作?
您发布的示例 link 尚未更新为最新更改(请注意边栏标题为 “示例(过时)”).
current docs for Async validators状态:
Async validators that return a Promise, need to be wrapped in the withAsync
helper. This will tell Vuelidate to treat the validator in a special way, tracking pending status, storing response and more:
//...
import { helpers } from '@vuelidate/validators'
const { withAsync } = helpers
export default {
setup() {
const state = reactive({
postcode: 'OX14 8JW'
})
const rules = {
postcode: {
startsWithX: withAsync(async (value) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
const isOk = value && value[0] === 'X'
return Boolean(isOk)
})
}
}
const v$ = useVuelidate(rules, state)
return { v$, state }
}
}
我正在尝试向 Vue 中的表单添加自定义异步验证并遵循 documented example,但验证永远不会失败。这是我的代码:
<script>
import { reactive } from 'vue';
import useVuelidate from '@vuelidate/core';
import { required, email } from '@vuelidate/validators';
export default {
template:
'<input v-model="state.postcode" /><div v-if="v$.postcode.$silentErrors.length">never shows</div>',
setup() {
const state = reactive({
postcode: 'OX14 8JW',
});
const rules = {
postcode: {
async startsWithX(value) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const isOk = value && value[0] === 'X';
// console.log('sanity check: ', isOk);
return Boolean(isOk);
},
},
};
const v$ = useVuelidate(rules, state);
return { v$, state };
},
};
</script>
谁能帮我让这个异步验证工作?
您发布的示例 link 尚未更新为最新更改(请注意边栏标题为 “示例(过时)”).
current docs for Async validators状态:
Async validators that return a Promise, need to be wrapped in the
withAsync
helper. This will tell Vuelidate to treat the validator in a special way, tracking pending status, storing response and more:
//...
import { helpers } from '@vuelidate/validators'
const { withAsync } = helpers
export default {
setup() {
const state = reactive({
postcode: 'OX14 8JW'
})
const rules = {
postcode: {
startsWithX: withAsync(async (value) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
const isOk = value && value[0] === 'X'
return Boolean(isOk)
})
}
}
const v$ = useVuelidate(rules, state)
return { v$, state }
}
}