<template> <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout"> <!-- 选择环境 --> <a-form-model-item label="切换环境" prop="huanjing"> <a-select placeholder="请选择环境" @change="handleChange"> <a-select-option value="dev"> dev </a-select-option> <a-select-option value="test"> test </a-select-option> <a-select-option value="staging"> staging </a-select-option> </a-select> </a-form-model-item> <!-- 内部账号id --> <a-form-model-item label="内部账号id" prop="zhanghao"> <a-input v-model="ruleForm.zhanghao" placeholder="请填写内部账号id"/> </a-form-model-item> <!-- 密码 --> <a-form-model-item label="Password" prop="pass"> <a-input-password v-model="ruleForm.pass" type="password" autocomplete="off" placeholder="必须包含字母、数字,8-16位"/> </a-form-model-item> <!-- 确认密码 --> <a-form-model-item label="Confirm" prop="checkPass"> <a-input-password v-model="ruleForm.checkPass" type="password" autocomplete="off" placeholder="请确认密码" /> </a-form-model-item> <!-- 提交和重置 --> <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }"> <a-button type="primary" @click="submitForm('ruleForm')"> Submit </a-button> <a-button style="margin-left: 10px" @click="resetForm('ruleForm')"> Reset </a-button> </a-form-model-item> </a-form-model> </template> <script> export default { data() { let validatePass = (rule, value, callback) => { if (value === '') { callback(new Error('该字段为必填')); } else { if (this.ruleForm.checkPass !== '') { this.$refs.ruleForm.validateField('checkPass'); } callback(); } }; let validatePass2 = (rule, value, callback) => { if (value === '') { callback(new Error('该字段为必填')); } else if (value !== this.ruleForm.pass) { callback(new Error("两次密码输入不一致")); } else { callback(); } }; return { ruleForm: { pass: '', checkPass: '', huanjing:'', zhanghao:'', }, rules: { pass: [ { validator: validatePass, trigger: 'change' }, { required: true, message: '该字段为必填' }, // { min: 8, max: 16, message: '长度在 8 到 16 个字符', trigger: 'change' }, { trigger: 'change', validator: (rule, value, callback) => { var passwordreg = /(?=.*d)(?=.*[a-zA-Z]).{8,16}/ if (!passwordreg.test(value)) { callback(new Error('密码必须由数字、字母组合,请输入8-16位')) }else{ callback() } } } ], checkPass: [ { validator: validatePass2, trigger: 'change' }, { required: true, message: '该字段为必填' }, ], huanjing:[ { required: true, message: '该字段为必填' }, ], zhanghao:[ { required: true, message: '该字段为必填' }, ], }, layout: { labelCol: { span: 4 }, wrapperCol: { span: 14 }, }, }; }, methods: { submitForm(formName) { this.$refs[formName].validate(valid => { if (valid) { // alert('submit!'); console.log(this.ruleForm) } else { // console.log('error submit!!'); return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); }, handleChange(e){ this.ruleForm.huanjing=e } }, }; </script>
表单的使用 https://www.antdv.com/components/form-model-cn/
密码组合校验: https://blog.csdn.net/qq_40295815/article/details/105433190