jQuery验证程序信用卡号+类型匹配 [英] jQuery Validator Credit Card Number + Type Match

查看:84
本文介绍了jQuery验证程序信用卡号+类型匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试添加一个客户jQuery验证器方法,该方法基本上检查卡类型和信用卡号的有效性.

Trying to add a customer jQuery validator method that basically checks the card type and the credit card number for validity.

即.如果类型为MasterCard,则卡号不是以5开头,否则无效;如果类型为Visa,如果卡号不是以4开头,则无效.我的公司只向MC或Visa收费,因此不需要其他任何收费.

ie. If the type is MasterCard, if the card number doesn't start with 5, it's invalid or if the type is Visa, if the card number doesn't start with 4, it's invalid. My company only charges MC or Visa, so no others are needed.

$.validator.addMethod("CCNumber", function(value, element, param) {
  if (param == "MasterCard") {
    return value.substring(0,1) != 5;   
  }
  else if (param == "Visa") {
    return value.substring(0,1) != 4;   
  }
});

在这里打电话:

cardnumber: {
  required: true,
  creditcard: true,
  minlength: 13,
  maxlength: 16,
  digits: true,
  CCNumber: function(){ return $('#cardtype').val(); }
},

还有消息...

cardnumber: {
  required: "Please enter a valid credit card number",
  minlength: "Please enter a valid credit card number",
  maxlength: "Please enter a valid credit card number",
  digits: "Your credit card number cannot contain spaces.",
  CCNumber: "WRONG"
},

最后,HTML:

<select name="cardtype" id="cardtype">
  <option value="MasterCard">MasterCard</option>
  <option value="Visa">Visa</option>
</select>

我以前从未写过jQuery方法,但是这里什么也没有发生.我不完全确定自己做错了什么,因为我尝试查看其他方法,但找不到任何东西.

I've never written a jQuery method before, but nothing is happening here. I'm not entirely sure what I've done wrong, as I've tried to look at other methods, but couldn't find anything.

推荐答案

jQuery验证插件已经有其他方法可用于这种情况.

The jQuery Validation plugin already has additional methods available for things like this.

以下是中使用的默认方法其他方法"文件,但仅针对Visa&万事达卡.

The following is the default method used in the "Additional Methods" file, but then edited down for only Visa & Mastercard.

jQuery.validator.addMethod("creditcardtypes", function(value, element, param) {
    if (/[^0-9-]+/.test(value)) {
        return false;
    }

    value = value.replace(/\D/g, "");

    var validTypes = 0x0000;

    if (param.mastercard)
        validTypes |= 0x0001;
    if (param.visa)
        validTypes |= 0x0002;

    if (validTypes & 0x0001 && /^(5[12345])/.test(value)) { //mastercard
        return value.length == 16;
    }
    if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
        return value.length == 16;
    }
    return false;
}, "Please enter a valid credit card number.");

这篇关于jQuery验证程序信用卡号+类型匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆