我正在尝试验证表单的USER ID。具体条件测试如下:
规则#1所有10个职位必须存在
规则#2位置5必须是连字符( - )
规则#3位置1到4必须是数字
规则#4位置6到10必须是数字 如果规则1到规则4已通过验证
,则只应检查以下两个规则(#5和#6)规则#5连字符( - )左边的数字之和必须大于零,连字符( - )右边的数字之和必须大于零
规则#6连字符( - )右边的数字之和必须是(双加2)连字符左边的数字之和( - )
您必须为不同的错误条件提供不同的消息
当我尝试执行此验证时,表单会在显示正确的错误消息时提交自己,我不确定为什么。
JavaScript函数:
function validateUserId() {
var value = document.getElementById("userId").value;
if (value.length != 10) {
errMessages += "User ID all 10 positions must be present";
return errMessages;
}
if (value[4] != "-") {
errMessages +="User ID Position 5 must be a hyphen (-)" ;
return errMessages;
}
for (var i = 0; i < 4; i++) {
if (isNaN(value[i])) {
errMessages += "User ID Position " + i + " must be a number" ;
return errMessages;
}
}
for (i = 5; i < 10; i++) {
if (isNaN(value[i])) {
errMessages += "User ID Position " + i + " must be a number" ;
}
}
var lowsum = 0;
for (i = 0; i < 4; i++) {
lowsum += parseInt(value[i]);
}
if (lowsum <= 0) {
errMessages += "User ID Sum of the first 4 numbers must be greater than 0" ;
return errMessages;
}
var highsum = 0;
for (i = 5; i < 10; i++) {
highsum += parseInt(value[i]);
}
if (highsum <= 0) {
errMessages += "User ID Sum of the last 5 numbers must be greater than 0" ;
return errMessages;
}
if (highsum != (lowsum * 2) + 2) {
errMessages += "User ID sum of the last 5 numbers must be the double plus of of the first 4 numbers" ;
return errMessages;
}
return errMessages;
}
HTML:
<label class="label">Client ID </label>
<input type="text" name="userId" id="userId" size="10" maxlength="10" >
答案 0 :(得分:0)
这看起来非常好。但您只需要return
false
。以这种方式更改您的代码:
function validateUserId() {
var value = document.getElementById("userId").value;
if (value.length != 10) {
errMessages += "User ID all 10 positions must be present";
alert(errMessages);
return false;
}
if (value[4] != "-") {
errMessages +="User ID Position 5 must be a hyphen (-)" ;
alert(errMessages);
return false;
}
for (var i = 0; i < 4; i++) {
if (isNaN(value[i])) {
errMessages += "User ID Position " + i + " must be a number" ;
alert(errMessages);
return false;
}
}
for (i = 5; i < 10; i++) {
if (isNaN(value[i])) {
errMessages += "User ID Position " + i + " must be a number" ;
}
}
var lowsum = 0;
for (i = 0; i < 4; i++) {
lowsum += parseInt(value[i]);
}
if (lowsum <= 0) {
errMessages += "User ID Sum of the first 4 numbers must be greater than 0" ;
alert(errMessages);
return false;
}
var highsum = 0;
for (i = 5; i < 10; i++) {
highsum += parseInt(value[i]);
}
if (highsum <= 0) {
errMessages += "User ID Sum of the last 5 numbers must be greater than 0" ;
alert(errMessages);
return false;
}
if (highsum != (lowsum * 2) + 2) {
errMessages += "User ID sum of the last 5 numbers must be the double plus of of the first 4 numbers" ;
alert(errMessages);
return false;
}
alert(errMessages);
}
<form onsubmit="return validateUserId()">
<input id="userId" />
<input type="submit" />
</form>