我有一个表单,如果用户名和密码为空或者不够长,我需要能够显示错误消息。我已经弄明白了,它正在发挥作用。我现在的问题是2倍。 #1如何在1个警报中显示多个错误? (使用数组??)如果输入正确,如何生成成功的警报。这是我的javascript和html。
<script>
function formIsValid(){
var validation = true;
validation &= checkUsername();
validation &= checkPassword();
return validation;
}
function checkUsername(){
var name= document.forms["RegistrationForm"]["user"].value;
var nameLength =name.length;
if(name == ""){
alert ("Please Enter a Username");
return false;
}
else if (nameLength <8){
alert ("The Username must be 8 characters");
return false;
}
}
function checkPassword(){
var password=document.forms["RegistrationForm"]["pass"].value;
var passwordLength =password.length;
if(password ==""){
alert ("Please Enter a Password");
return false;
}
else if (passwordLength <8){
alert ("The Password must be 8 characters");
return false;
}
}
</script>
Html代码
<form name="RegistrationForm" onsubmit="return formIsValid()" action="">
<h2>Registration</h2>
Username:<input type="text" name="user" size="20"/> (At least 8 characters)<br/>
<br/>
Password:<input type="text" name="pass" size="20"/> (At least 8 Characters)<br/>
<br/>
<input type="submit" value="Submit">
<input type="reset" name="reset" value="Clear"/>
<p>
</form>
答案 0 :(得分:0)
也许有点像这样:
function checkPassword(errors){
...
if (password == "") {
errors.push("Please Enter a Password");
} else if (passwordLength <8){
errors.push("The Password must be 8 characters");
}
return errors;
}
然后您的调用方法可能如下所示:
function formIsValid(){
var errors = [];
errors = checkUsername(errors);
errors = checkPassword(errors);
if (errors.length == 0) alert('win');
else alert(errors.join('\r\n'));
}
答案 1 :(得分:0)
尝试以下代码,它应该按照您想要的方式工作。 :)
<html>
<head>
<script>
var userFlag =true;
var passFlag = true;
var msg = "";
function formIsValid(){
checkUsername();
checkPassword();
if(passFlag && userFlag ){
return true;
}
else{
alert (msg);
msg="";
return false;
}
}
function checkUsername(){
var name= document.forms["RegistrationForm"]["user"].value;
var nameLength =name.length;
if(name == ""){
msg +="Please Enter a Username";
userFlag = false;
}
else if (nameLength <8){
msg +="The Username must be 8 characters";
userFlag = false;
}
}
function checkPassword(){
var password=document.forms["RegistrationForm"]["pass"].value;
var passwordLength =password.length;
if(password ==""){
msg += " and Please Enter a Password";
passFlag = false;
}
else if (passwordLength <8){
msg += "and The Password must be 8 characters";
passFlag = false;
}
}
</script>
</head>
<body>
<form name="RegistrationForm" onsubmit="return formIsValid()" action="">
<h2>Registration</h2>
Username:<input type="text" name="user" size="20"/> (At least 8 characters)<br/>
<br/>
Password:<input type="text" name="pass" size="20"/> (At least 8 Characters)<br/>
<br/>
<input type="submit" value="Submit">
<input type="reset" name="reset" value="Clear"/>
</form>
</body>
</html>