I have a register form with next fields:
What I want is:
If I want to create a user with student role, optional field should not be considered , but if I want to create a professor/secretary user, then I will have to type a certain password in optional field ( https://prnt.sc/159y5x9 )
This is my Register function:
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 using React and Material UI TextField
You can do something like this
// validation for Optional field here //
if(role === "professor" || role === "secretary "){
if (isEmpty(optional)) {
return setUser({ ...user, err: "Optional field is required", success: "" });
}
}
or
// validation for Optional field here //
if(!isEmpty(role) && role !== "student"){
if (isEmpty(optional)) {
return setUser({ ...user, err: "Optional field is required", success: "" });
}
}
or
// validation for Optional field here //
if(!isEmpty(role) && role !== "student" && isEmpty(optional)){
return setUser({ ...user, err: "Optional field is required", success: "" });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.