我目前有一些验证,如果用户输入的值少于7个字符,则返回false:
if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 ) {
alert("Invalid Cost Centre");
return false;
}
我需要做的是在同一元素中添加进一步验证,如果#txt-centre
没有以&#39; 212&#39;
答案 0 :(得分:3)
我可能会使用像
这样的正则表达式if (nextPgeNum == 3 && !/^212.{4,}/.test($('#txt-centre').val())) {
alert("Invalid Cost Centre");
return false;
}
答案 1 :(得分:2)
为简单起见,我建议使用indexOf()
:
if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 && $('#txt-centre').val().indexOf('212') === 0) {
alert("Invalid Cost Centre");
return false;
}
可能值得缓存该值,因为它被访问两次,并且还删除了前导/尾随空格(使用$.trim()
或String.prototype.trim()
):
var value = $.trim($('#txt-centre').val());
if (nextPgeNum == 3 && value.length < 7 && value.indexOf('212') === 0) {
alert("Invalid Cost Centre");
return false;
}
答案 2 :(得分:1)
试试这个:
if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 && !$('#txt-centre').val().startsWith("212")) {
这是基本的JavaScript。
答案 3 :(得分:0)
具有良好浏览器支持的最直接的解决方案是substring
:
var val = $('#txt-centre').val();
if (nextPgeNum == 3 && val.length < 7 && val.substring(0, 3) !== "212") {
alert("Invalid Cost Centre");
return false;
}
我想你想!==
......