我有两个 if/else 语句在一个函数中比较同一个变量。我不希望,也没有理由嵌套这些语句。
function checkUser() {
var user = document.getElementById('usern').value;
var element = document.getElementById('labelUser');
if (user.length < 3 || user.length > 15) {
element.innerHTML = "Invalid length.";
element.style.color = "red";
}
else {
element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';
}
if (user.match(/[\<\>!@#\$%^&\*,]+/i)){
element.innerHTML = "Invalid characters.";
element.style.color = "red";
}
else {
element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';
}
}
如何改进此代码?