我使用以下代码进行了javascript表单验证。我不确定它是否是验证表单的正确方法。
const signup=()=>{
let name=document.querySelector("#u_name").value;
let email=document.querySelector("#email_id").value;
let password=document.querySelector("#pwd").value;
let confirmPassword=document.querySelector("#confirm_pwd").value;
let i=0;
if((name==""||email=="")||(password==""||confirmPassword==""))
{
document.querySelector("#empty-field").innerHTML="*Fill all required fields";
i++;
}
else
{
if(name.length<3)
{
document.querySelector("#u_name").style.borderColor="red";
document.querySelector("#user-errmsg").innerHTML="*Enter valid user name";
i++;
}
else
{
document.querySelector("#u_name").style.borderColor="#ced4da";
document.querySelector("#user-errmsg").innerHTML="";
i;
}
if(email.length<6)
{
document.querySelector("#email_id").style.borderColor="red";
document.querySelector("#email-errmsg").innerHTML="*Enter valid email id";
i++;
}
else
{
document.querySelector("#email_id").style.borderColor="#ced4da";
document.querySelector("#email-errmsg").innerHTML="";
i;
}
if(password.length<6 && confirmPassword.length<6)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length<6 && confirmPassword.length>=6)
{
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Password must be atleast 6 digits long";
i++;
}
else if(password.length>=6 && confirmPassword.length>=6)
{
if(password!= confirmPassword)
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
else
{
document.querySelector("#pwd").style.borderColor="#ced4da";
document.querySelector("#confirm_pwd").style.borderColor="#ced4da";
document.querySelector("#pwd-errmsg").innerHTML="";
i;
}
}
else
{
document.querySelector("#pwd").style.borderColor="red";
document.querySelector("#confirm_pwd").style.borderColor="red";
document.querySelector("#pwd-errmsg").innerHTML="*Both fields must have the same password";
i++;
}
document.querySelector("#empty-field").innerHTML="";
}
if(i==0)
return true;
else
return false
}
写下太多if else条件是一个好习惯吗?如果没有,我该如何重写呢?
//忽略
看起来stackoverflow不允许用较少的细节发布这个问题:/所以我必须添加更多的东西。
答案 0 :(得分:1)
您的代码将从将所有内容提取到函数中受益:
const get = selector => document.querySelector(selector);
const checker = (check, msg) => (el, error) => {
if(check(get(el).value)){
get(el).style.color = "green";
get(error).innerHTML = "";
return true;
} else {
get(el).style.color = "red";
get(error).innerHTML = msg;
}
};
const minLength = length => checker(
v => v.length >= length,
`Too short! You need at least ${length} chars`
);
const maxLength = length => checker(
v => v.length <= length,
`Too long! You need less than ${length} chars`
);
const equal = (a, b, err) => checker(v => v === get(b).value, "They must be equal")(a, err);
似乎很长吧?但现在你可以这样做:
return (
minLength(6)("#u_name", "#user-errmsg") &&
maxLength(12)("#u_name", "#user-errmsg") &&
minLength(6)("#email_id", "#email-errmsg") &&
equal("#confirm_pwd", "#pwd", "#pwd-errmsg")
)
答案 1 :(得分:0)
您对在单个方法范围内使用过多if / else语句的担忧是有效的。这没有错,但如果出现问题,使代码难以阅读/理解,难以调试/排除故障。以下是重构此方法的一些建议:
validate
或类似的内容。validateEmailAddress()
或validatePassword()
。一旦你开始移动棋子,你将获得更少的if / elseif语句。你可以做更多的事情,但关键在于脱钩责任。如果您尝试,我相信您的if / elseif金额会减少。
我总是使用另一种策略来删除if / else嵌套级别,通常称为early return。
答案 2 :(得分:0)
使用jquery插件https://jqueryvalidation.org/
以下是使用示例:
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "myform"
$("form[name='myform']").validate({
// Specify validation rules
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 8 characters long"
},
email: "Please enter a valid email"
},
submitHandler: function(form) {
form.submit();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<div>
<h2>Sign Up</h2>
<form action="" name="myform">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="Robert" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="Smith" />
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="name@company.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="" />
<button type="submit">Submit</button>
</form>
</div>
label.error {
color: red;
margin-top:-10px;
margin-bottom:15px;
}
答案 3 :(得分:0)
您不需要任何javascript验证或额外的库,只需使用字段上所需的所有属性并更正类型。使用“约束验证”。您需要检查的是密码是否匹配(显示如何在下面)
在此处研究输入属性:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
function validatePassword(){
const pwd1 = document.getElementById("pwd")
const pwd2 = document.getElementById("confirm_pwd")
pwd1.setCustomValidity(pwd1.value !== pwd2.value
? "Passwords Don't Match"
: ""
)
}
document.getElementById("pwd").oninput = validatePassword
document.getElementById("confirm_pwd").oninput = validatePassword
input:not([type=submit]):valid {
border: 1px solid lime;
}
<form class="" action="index.html" method="post">
<br>name<br>
<input name="" required type="text" autocomplete="name" minlength="3" id="u_name">
<br>email<br>
<input name="" required type="email" autocomplete="email" id="email_id">
<br>pwd<br>
<input name="" required type="password" autocomplete="new-password" minlength="6" id="pwd">
<br>repeat pwd<br>
<input name="" required type="password" autocomplete="new-password" minlength="6" id="confirm_pwd">
<br><input type="submit">
</form>
我个人觉得重复电子邮件和/或密码非常累。如果我弄错了,我会再次进行或按“忘记密码”链接。我可以看到我的电子邮件地址,并且在自动填充的帮助下,我的电子邮件出错的风险较低。你不需要每个其他网站的b / c剂量。如果这样你就不需要任何javascript ......