【发布时间】:2020-07-04 09:12:35
【问题描述】:
我正在尝试使用 useState() 和 useEffect() 验证表单
这是我的 useEffect() 方法:
/ for every change in our state this will be fired
// we add validation here and disable the save button if required
useEffect(() => {
// we want to skip validation on first render
if (firstRender.current) {
firstRender.current = false
return
}
// here we can disable/enable the save button by wrapping the setState function
// in a call to the validation function which returns true/false
//setDisabled(formValidation())
formValidation();
}, [fullName,email,password]) // any state variable(s) included in here will trigger the effect to run
`我是 React JS 的新手,所以使用 if-else 完成了基本的编码。 我在这里停留的概念比技术更多。 我无法验证其他输入字段,例如电子邮件和密码。如何实现? 这是我的验证方法: // 这里我们运行任何验证,返回真/假
const formValidation = () => {
var error = false;
if (fullName === "") {
setNameError('Name cant be blank!')
error = true;
}
let regEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!regEmail.test.email) {
setEmailError('Enter a valid email id')
error = true;
}
if (email === "") {
setEmailError('Mandatory Field')
error = true;
}
let regPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/
if (!regPassword.test.email) {
// alert("errosdr")
setPasswordError('Invalid Password Format')
error = true;
}
if (error == true) {
return true;
}
else {
setNameError(null)
setEmailError(null)
setPasswordError(null)
return false
}
}
第一个字段的验证效果很好,即 fullName。
仅供参考,这里是useState()的定义
// we use the help of useRef to test if it's the first render
const firstRender = useRef(true);
// set a state variable which can be used to disable the save/submit button
// we set it to true so that the form is disabled on first render
const [disable, setDisabled] = useState(true);
// set error messages to display to the user
const [nameError, setNameError] = useState(null);
const [emailError, setEmailError] = useState(null);
const [passwordError, setPasswordError] = useState(null);
// set initial state value(s)
const [fullName, setFullName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
【问题讨论】:
-
将
Formik与yup库一起使用,以便更轻松地验证表单处理。 -
@adel 感谢您的告知。现在,希望以正常方式进行。 :)
标签: javascript reactjs validation