javascript - How can I optimize my validation code in reactjs?
问题描述
Below, I have mentioned my JS code. So, Kindly suggest or guide me that there is any better approach to implement the validation on form submit for react project or is it right approach which i have implemented already?
submitUserForm = (e) => {
e.preventDefault();
const { formError } = this.state;
let valid = true;
if(document.getElementById('useremail').value === "") {
valid = false;
formError.email = "Kindly enter your email id"
}
else {
valid = true;
formError.email = ""
}
if(document.getElementById('userpassword').value === "") {
valid = false;
formError.password = "Kindly enter the password"
}
else {
valid = true;
formError.password = ""
}
if(valid === true) {
this.formSubmitApi();
}
this.setState({
isValid: valid,
formError
})
}
解决方案
这是改进代码的方法:
submitUserForm = (e) => {
e.preventDefault();
const formError = {}
if(document.getElementById('useremail').value === "") {
formError.email = "Kindly enter your email id"
}
if(document.getElementById('userpassword').value === "") {
formError.password = "Kindly enter the password"
}
Object.keys(formError).length === 0 && this.formSubmitApi();
this.setState({
formError
})
}
推荐阅读
- android - java.lang.NumberFormatException: Invalid int: "null" android studio
- cron - 当另一个程序使 cronjob 中的命令失败时,我如何使用 cronjob?
- javascript - 如何根据点击记录两个值并设置一个新函数对其进行操作
- python - python的不同终端命令行
- etsy - 客人购物车选择的变体在 Etsy API 中不起作用
- if-statement - 使用 IF 语句引用另一个单元格时,在 IF 语句中未获得预期结果
- excel - Excel VBA 循环遍历数据并复制行
- php - Foreach 循环:排除显示的值
- python - python上的SMTP utf-8错误
- reactjs - 部署到 Heroku 时如何在没有 create-react-app 的情况下在 React 应用程序中设置代理