我想只使用字母并限制编号。0到10之间的字母。我为它写正则表达式,但它不能正常工作。实际上,它匹配得很好,当我输入除字母以外的任何其他字符时,它会给出错误,但当我超过最大限制(即10)时,它不会给出任何错误。
我的代码-
$(document).ready(function() {
$("#name").keypress(function (e) {
var keyCode = e.keyCode || e.which;
$("#nameError").html("");
//Regex for Valid Characters i.e. Alphabets.
var regex = /^[A-Za-z]{0,10}$/;
//Validate TextBox value against the Regex.
var isValid = regex.test(String.fromCharCode(keyCode));
if (!isValid) {
$("#nameError").html("Only Alphabets allowed and range is between 0 to 10.");
}
return isValid;
});
});
您在交叉10个字符时没有得到错误的原因是因为这部分var isValid = regex.test(String.fromCharCode(keyCode));
只检查您输入的字符,这是1个字符。
您可以做的是检查您添加的1个字符是否在A-Za-z范围内,然后使用正则表达式^[A-Za-z]{0,10}$
检查输入的字符加上输入字段中已经存在的内容。
$(document).ready(function() {
var name = $("#name");
var nameError = $("#nameError");
name.keypress(function(e) {
var keyCode = e.keyCode || e.which;
nameError.html("");
//Regex for Valid Characters i.e. Alphabets.
var regex = /^[A-Za-z]{0,10}$/;
//Validate TextBox value against the Regex.
var newChar = String.fromCharCode(keyCode);
var isValidLength = regex.test(newChar + name.val());
var isValidChar = /^[A-Za-z]$/.test(String.fromCharCode(keyCode));
if (!isValidChar || !isValidLength) {
nameError.html("Only Alphabets allowed and range is between 0 to 10.");
}
return isValidChar && isValidLength;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="name">
</form>
<div id="nameError"></div>
代码中的注释说:
// Validate TextBox value against the Regex.
var isValid = regex.test(String.fromCharCode(keyCode));
但是您只验证按下的键中的单个字符。
试题:
// Validate TextBox value against the Regex.
var isValid = regex.test($("#name").val());
而且,只是为了好玩,这里是一个简短的版本,使事情变得简单:
$(document).ready(() => {
$("#name").keypress(e => /^[A-Za-z]{0,10}$/.test(
$("#name").val() + String.fromCharCode(e.which)
));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name">
如果regex测试失败,事件处理程序将返回false并阻止显示该字符。