你可以使用一个单一的输入,设置maxlenght,这将只允许16个字符被放入文本框中。然后测试一下这个长度,并且所有的字符都是带有javascript的数字。
HTML
<input type="text" name="ccn" maxlength="16" id="ccn">
的Javascript
var ccn = $('#ccn').val();
//Test the length, and use a regex to test
//that there are 16 numbers
if(ccn.length < 16 || !/[0-9]{16}/.test(ccn)) {
//Invalid credit card number do error code here
}
或与每个中设置最大长度4的分组输入下榻,并测试每一个长度和有效数字
HTML
<input type="text" name="ccn1" maxlength="4" id="ccn1">
<input type="text" name="ccn2" maxlength="4" id="ccn2">
<input type="text" name="ccn3" maxlength="4" id="ccn3">
<input type="text" name="ccn4" maxlength="4" id="ccn4">
的Javascript
function is_ccnGroup(group) {
if(group.length < 4 || !/[0-9]{4}/.test(group)) {
return false;
}
return true;
}
if(is_ccnGroup($('#ccn1').val()) &&
is_ccnGroup($('#ccn2').val()) &&
is_ccnGroup($('#ccn3').val()) &&
is_ccnGroup($('#ccn4').val())) {
// All the groups seem to be valid
} else {
//One or more of the groups are invalid
}
大概也可以使用jQuery的.map
功能,以减少代码的4组的方式。
<input type='number' pattern='.{16}' />
注意,并不是所有的浏览器都支持type='number'
或pattern
但我相信,最近的所有主流浏览器做版本:
在哪里你检查数字? – putvande
您所做的只是检查输入的值是否为空字符串......所以您的代码按设计工作! –
这只是检查空。阅读此:http://stackoverflow.com/questions/4514430/credit-card-checksums-and-validations-that-do-not-require-connection-to-the-fina –