我编写了一些
JavaScript和jQuery代码,只接受文本框中的数字输入.
但这还不够;我需要将输入限制为某些数字.
这个文本框需要处理SSN号码(瑞典SSN),它必须从19或20开始.我想强制它从这些数字开始,但我不能设法限制它们.
$('input.SSNTB').keydown(function (event) {
var maxNrOfChars = 12;
var ssnNr = $('input.SSNTB').val();
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))) {
console.log("if-1");
event.preventDefault();
}
if (event.shiftKey == true) {
console.log("if-3");
event.preventDefault();
}
//rules to make sure the textbox starts with correct number
if (event.keyCode != 49 || event.keyCode != 50 || event.keyCode != 97 || event.keyCode != 98) {
console.log("if-4, Keycode:" + event.keyCode);
event.preventDefault();
}
}
});
执行最后一个if-case以进行测试.它按计划执行,但它不会限制输入字符作为其构建.
任何提示或想法?
最佳答案 您可以使用正则表达式将用户限制为仅输入数字和短划线.使用正则表达式的优势在于用户可以更自然地与输入进行交互,例如,他们可以粘贴到文本输入中,并且将成功验证:
//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {
//get the newly changed value and limit it to numbers and hyphens
var newValue = this.value.replace(/[^0-9\-]/gi, '');
//if the new value has changed, meaning invalid characters have been removed, then update the value
if (this.value != newValue) {
this.value = newValue;
}
}).on('blur', function () {
//run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
alert('ERROR!');
} else {
alert('GOOD GOING!');
}
});
这是一个演示:http://jsfiddle.net/BRewB/2/
请注意.on()是jQuery 1.7中的新增内容,在这种情况下与使用.bind()相同.