[英]validating using input.value.match in javascript
I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. 我相信我有一个相当简单的问题,但不幸的是我无法解决。 I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
我搜索了一段时间,并尝试了该代码的几种不同变体,但似乎无法使其正常工作。
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number. 我要做的只是检查并查看我的输入值中是否有与数字相反的字母字符。
Here is my js function: 这是我的js函数:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it: 这是调用它的代码:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated. 任何帮助或建议,将不胜感激。
You're passing cc_number.value
as input
, but then referencing input.value.match()
, which works out to: 您正在传递
cc_number.value
作为input
,但随后引用了input.value.match()
,其结果是:
cc_number.value.value.match();
Just pass cc_number
: 只需传递
cc_number
:
if (checkLetters(cc_number)) {
...
}
It looks like you're trying to validate credit card input. 您似乎正在尝试验证信用卡输入。 May I suggest a different approach?
我可以建议其他方法吗?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use. 有关示例用法,请参见此jsFiddle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.