我有一个文本框和一个提交按钮
<input type="text" name="username" id="username"/><br/>
<input type="submit" onclick="return validate()"/>
这是功能代码:
if (document.getElementById("usernameee").value == null || document.getElementById("usernameee").value == "" ) {
document.getElementById("usernameee").style.borderColor = 'red';
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
if (document.getElementById("usernameee").value.length!=0 || document.getElementById("usernameee").value.length < 8 ) {
document.getElementById("usernameee").style.borderColor = 'red';
document.getElementById("message").innerHTML="Enter Atleast 8 Characters"
return false
} else {
document.getElementById("usernameee").style.borderColor = '';
}
现在需要的是,如果用户将字段留空,则应仅突出显示文本框,背景颜色为红色,如果用户名少于8个字符,则应显示该消息并突出显示文本框的背景但现在即使文本框为空它显示我不想要的消息...如果该字段为空它应该
答案 0 :(得分:0)
我认为你的第二个条件是错误的。你也可以像这样编写更清晰的代码:
var username = document.getElementById("usernameee");
if(!username.value) {
//There is no username
username.style.borderColor = 'red';
} else if(username.value.length < 8) {
//There is a username and the value is shorter than 8 characters
username.style.borderColor = 'red';
document.getElementById("message").innerHTML = "Enter Atleast 8 Characters";
} else {
//There is a username and it is longer than or equal to 8 characters.
username.style.borderColor = '';
document.getElementById("message").innerHTML = "";
}