我有一个带有下一个字段的注册表单:
- 名称
- 电子邮件
- 密码
- 确认密码
- 可选字段
- 选择角色(学生、教授、秘书(
我想要的是:
如果我想创建一个具有学生角色的用户,则不应考虑可选字段,但如果我要创建教授/秘书用户,则我必须在可选字段中键入特定密码(https://prnt.sc/159y5x9)
这是我的注册功能:
function Register() {
const [user, setUser] = useState(initialState)
const pswdProfesor = "profpassword" //password needed for professor role
const pswdSecretar = "secretpasswor" // password needed for secretary role
const {name, email, password,cf_password, role, err, success} = user
const handleChangeInput = e => {
const {name, value} = e.target
setUser({...user, [name]:value, err: '', success: ''})
}
const handleSubmit = async e => {
e.preventDefault()
if(isEmpty(name) || isEmpty(password) || isEmpty(role))
return setUser({...user, err: "Completati campurile", success: ''})
if(!isEmail(email))
return setUser({...user, err: "Email invalid", success: ''})
if(isLength(password))
return setUser({...user, err: "Parola trebuie sa fie minim 6 caractere", success: ''})
if(!isMatch(password, cf_password))
return setUser({...user, err: "Parola nu coincide", success: ''})
// validation for Optional field here //
try {
const res = await axios.post('/user/register', {
name, email, password, role
})
setUser({...user, err: '', success: res.data.msg})
} catch (err) {
console.log("hello")
err.response.data.msg &&
setUser({...user, err: err.response.data.msg, success: ''})
}
}
PS:im使用React和Material UI TextField
您可以执行类似的操作
// validation for Optional field here //
if(role === "professor" || role === "secretary "){
if (isEmpty(optional)) {
return setUser({ ...user, err: "Optional field is required", success: "" });
}
}
或
// validation for Optional field here //
if(!isEmpty(role) && role !== "student"){
if (isEmpty(optional)) {
return setUser({ ...user, err: "Optional field is required", success: "" });
}
}
或
// validation for Optional field here //
if(!isEmpty(role) && role !== "student" && isEmpty(optional)){
return setUser({ ...user, err: "Optional field is required", success: "" });
}