官网:
NutUI - 移动端 Vue2、Vue3、小程序 组件库京东风格的轻量级移动端 Vue、React 组件库https://nutui.jd.com/#/component/form
(详细的代码在下面,这里先只说主要的使用方法)
如果.validate()里的参数是空,则默认校验全部规则
ruleForm.value.validate().then(async ({ valid, errors }: any) => {}
如果想单独使用某一个规则的话。就在.validate()里面加上要验证的那个prop参数即可:比如只想校验手机号码的话:
ruleForm.value.validate(formData.phone).then(async ({ valid, errors }: any) => {}
关键代码:
- <template>
- <div class="login">
- <nut-form ref="ruleForm" :model-value="formData">
- <nut-form-item
- required
- prop="phone"
- :rules="[
- { required: true, message: '请输入手机号码' },
- { validator: validatePhone, message: '请输入正确的手机号' },
- ]"
- >
- <nut-input v-model="formData.phone" class="nut-input-text" placeholder="请输入手机号码" type="tel" />
- </nut-form-item>
- <nut-form-item
- required
- prop="verificationCode"
- :rules="[
- { required: true, message: '请输入短信验证码' },
- { validator: validatePhoneMsg, message: '请输入正确的短信验证码' },
- ]"
- >
- <nut-input v-model="formData.verificationCode" class="nut-input-text verification-code-input fl" placeholder="请输入短信验证码" type="password" />
- <nut-button class="verification-code-btn fr" size="small" type="info" @click="handleGetCheckCode" :disabled="!checkCodeBtnCanClick">
- {{ pageData.btnTimes ? pageData.btnTimes + 'S' : '发送验证码' }}
- </nut-button>
- </nut-form-item>
- <nut-button block type="info" class="login-btn" @click="submit"> 登录/注册 </nut-button>
- </nut-form>
- </div>
- </template>
-
- <script lang="ts" setup>
- import router from '/@/router';
- import { computed, reactive, ref } from 'vue';
- import { useUserStore } from '/@/store/modules/user';
- import { login, test, sendMsg } from '/@/api';
- import { Toast } from 'vant';
- });
- const formData = reactive({
- phone: '',
- verificationCode: '', // 短信验证码
- });
- const ruleForm = ref<any>(null);
- const submit = () => {
- ruleForm.value.validate().then(async ({ valid, errors }: any) => {
- if (valid) {
-
- } else {
- console.log('error submit!!', errors);
- }
- });
- };
- const handleGetCheckCode = () => {
- ruleForm.value.validate(formData.phone).then(async ({ valid, errors }: any) => {
- if (valid) {
-
- } else {
- console.log('error!!', errors);
- }
- });
- };
-
- // 函数校验
- // 验证手机号
- const validatePhone = (value: any) => {
- if (!value || !value.trim()) {
- Toast.fail(new Error('请输入手机号码'));
- } else {
- const reg = /^1[0-9]\d{9}$/;
- if (reg.test(value)) {
- return true;
- } else {
- Toast.fail(new Error('请输入正确的手机号'));
- }
- }
- };
- // 自定义短信验证码验证方法
- const validatePhoneMsg = (value: any) => {
- console.log('自定义短信验证码验证方法', value);
- if (!value || !value.trim()) {
- Toast.fail(new Error('请输入短信验证码'));
- } else {
- const reg = /^[0-9]{6}$/;
- if (reg.test(value)) {
- return true;
- } else {
- Toast.fail(new Error('请输入正确的短信验证码'));
- }
- }
- };
- </script>
以文档的这个例子来改写:
官网的代码可以运行: