【发布时间】:2012-10-14 21:24:05
【问题描述】:
以下检查通过由字母 A-F 和数字 0-9 以及三个短划线(“-”)组成的 35 个字符组成的输入提交的项目代码。有效项目代码的示例如下:16FA860F-E86A457B-A28A238B-2ACA6E3D
//Checks the item code to see if it meets requirements
if($("#input").val().length > 35) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> is too long.<br>");
$("#ise").each(function(){
this.reset();
});
}
else if($("#input").val().length < 35) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> is too short. Be sure to include dashes.<br>");
$("#ise").each(function(){
this.reset();
});
}
else if($("#input").val().match(/([^A-Fa-f0-9-]+)/gm)) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> contains invalid characters.<br>");
$("#ise").each(function(){
this.reset();
});
}
else if($("#input").val().match(/[-]/g, "").length > 3) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> is an invalid format. Please only use 3 dashes.<br>");
$("#ise").each(function(){
this.reset();
});
}
else if($("#input").val().match(/[-]/g, "").length < 3) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> is an invalid format. Please include 3 dashes.<br>");
$("#ise").each(function(){
this.reset();
});
}
else {
//Rest of my code
}
以下内容运行良好,除非项目代码长度为 35 个字符,但不包含破折号。如果它包含 1 或 2 个破折号,那么这段代码会捕获它,但如果它包含 0,那么它就会挂起并且什么也不做。我几乎尝试了所有方法,但似乎无法弄清楚解决方案可能是什么。由于长度为空,它只是挂起。应该以某种方式调整的部分是这样的:
else if($("#input").val().match(/[-]/g, "").length > 3) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> is an invalid format. Please only use 3 dashes.<br>");
$("#ise").each(function(){
this.reset();
});
}
else if($("#input").val().match(/[-]/g, "").length < 3) {
$("#errorLogContent").prepend("The item code <font color='#FFFFFF'>" + itemCode + "</font> is an invalid format. Please include 3 dashes.<br>");
$("#ise").each(function(){
this.reset();
});
}
我确信解决方案很简单,但我很难过。
编辑:这是我对大部分内容的布局方式,除了 CSS。 http://jsfiddle.net/86KcG/1/
【问题讨论】:
-
看起来你过于复杂了。格式总是一样的吗?也就是说,
-总是在同一个位置吗?一个正则表达式就可以完成这项工作...... -
如果长度为 35 应该启动哪个条件??
-
@Michael 是的,但我现在不太担心检查它,尽管它会很好。我专注于确保代码中始终存在三个破折号,如果没有,则给出错误消息。如果只有 1 或 2 个,它会起作用,但如果没有,则它什么也不做。
-
@jfriend00 实际上 jQuery 没有
reset()方法,除非它只是在 1.8 中添加的。$("#ise")[0].reset();会更合适 -
.length永远不会是null。match()的返回值可能是null,在这种情况下,如果您尝试检查length属性,则会收到错误消息(但length本身将始终是来自0或 @987654334 的整数@)。
标签: javascript jquery regex if-statement null