使用开关案例验证表单
我正在创建一个具有2个条件的表单验证。这是使用Switch Case与其他语句使用Switch Case的好方法吗?还是这是皱眉?如果是这样,在不使用外部库的情况下,可以更好地解决此问题的方法,谢谢。
代码:
const validate = ( name, value) => {
switch (name) {
case "user_name":
if (!value) {
setErrors({ ...errors, user_name: "Please, submit required data" });
} else if (!new RegExp(/^[A-Za-z0-9]+$/).test(value)) {
setErrors({
...errors,
user_name: "Please, provide the data of indicated type(no special characters)",
});
} else {
let newObj = omit(errors, "user_name");
setErrors({ ...newObj });
}
break;
.....
I am creating a form validation with 2 conditions to validate. Is this a good way to use switch case with if else statement? Or is this something that is frown upon? If so, what would a better way to approach this without using external library, thank you.
Code:
const validate = ( name, value) => {
switch (name) {
case "user_name":
if (!value) {
setErrors({ ...errors, user_name: "Please, submit required data" });
} else if (!new RegExp(/^[A-Za-z0-9]+$/).test(value)) {
setErrors({
...errors,
user_name: "Please, provide the data of indicated type(no special characters)",
});
} else {
let newObj = omit(errors, "user_name");
setErrors({ ...newObj });
}
break;
.....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不是很可读,所以我不会说这是最好的方法,但绝对不是最糟糕的方法。您可以尝试这样的事情。
It's not very readable so I wouldn't say it's the best way, but it's definitely not the worst. You could try something like this.