我编写了一些 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()
相同。
关于javascript - 使用 JavaScript 只允许 HTML 输入中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8983402/