我有一个像这样的JQuery代码:
// Validation to avoid non alphanumeric characters from being typed
function alphanumeric(eventSource) {
var numaric = eventSource.val();
for (var j = 0; j < numaric.length; j++) {
var alphaa = numaric.charAt(j);
var hh = alphaa.charCodeAt(0);
// If the value contains non alphanumeric characters
if (!((hh > 47 && hh < 58) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123))) {
eventSource.val(numaric.substring(0, j) + numaric.substring(j + 1, numaric.length));
}
}
}
我正在尝试验证文本框输入的特殊字符。 但不知何故,它还验证了空格(键盘上的空格键),其中char代码为32。 建议,谢谢。
答案 0 :(得分:1)
试试此代码
var regtest = 'dfdsfdsf23424';
var letters = /^[a-zA-Z0-9]+$/;
var result = letters.test(regtest );
console.log(result);//true
regtest = 'dfdsfdsf 23424';
result = letters.test(regtest );
console.log(result);//false
测试小提琴http://jsfiddle.net/Stw2Y/
对于你的功能,你将避免使用特殊字符,然后尝试这个
var letters = /^[a-zA-Z0-9]+$/;
function alphanumeric(eventSource) {
var numaric = eventSource.val();
var str='';
for (var j = 0; j < numaric.length; j++) {
var alphaa = numaric.charAt(j);
// If the value contains non alphanumeric characters
if(letters.test(alphaa))
{
str+=alphaa;
}
}
eventSource.val(str);
}
答案 1 :(得分:1)
试试这个:
function alphanumeric(eventSource) {
var numaric = eventSource.val();
for (var j = 0; j < numaric.length; j++) {
var alphaa = numaric.charAt(j);
var hh = String.charCodeAt(alphaa);
// If the value contains non alphanumeric characters
if (hh != 32 && !((hh > 47 && hh < 58) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123))) {
eventSource.val(numaric.substring(0, j) + numaric.substring(j + 1, numaric.length));
}
}
}