我正在尝试编写一个自定义方法,如下所示,使用jQuery验证来验证信用卡号。
jQuery.validator.addMethod("ValidateCreditCard", function(value, element, params) {
var selectedElement = $('input[name="CardType"]');
var cardType = selectedElement.filter(':checked').val();
var cardNumber = $("#CardNumber").val();
if (cardType == "MasterCard" && !value.startsWith(5)) {
return false;
}
if (cardType == "Visa" && !value.startsWith(4)) {
return false;
}
return true;
}, jQuery.validator.format("Please enter a {0} card number"));
根据卡片类型的单选按钮选择,我想显示相应的消息。 例如,如果用户选择了Visa信用卡,那么请输入错误信息,请输入一张同样适用于Master信用卡的签证卡号
有关如何传递卡片类型值以格式化邮件的任何想法?
答案 0 :(得分:2)
你可以这样做:
<强> HTML 强>
<form id="CHECKFORM" name="CHECKFORM">
<div>
<input type="radio" name="CardType" id="radioVisaCard" value="Visa" />
<label for="MOBILE">Visa</label>
<input type="radio" name="CardType" id="radioMasterCard" value="MasterCard" />
<label for="MOBILE">Master</label>
<input type="text" class="cardNumber" data-rule-validatecreditcard="true" />
</div>
<input type="submit" value="submit" />
</form>
<强> JS 强>
<script>
jQuery.validator.addMethod("ValidateCreditCard", function (value, element) {
var selectedElement = $('input[name="CardType"]');
var cardType = selectedElement.filter(':checked').val();
if (cardType == "MasterCard" && !value.startsWith(5)) {
return false;
}
if (cardType == "Visa" && !value.startsWith(4)) {
return false;
}
return true;
}, function (element) {
var selectedElement = $('input[name="CardType"]');
var cardType = selectedElement.filter(':checked').val();
var startDigit;
if (cardType == "MasterCard")
startDigit = 5;
else if (cardType == "Visa")
startDigit = 4;
return 'The field should be start with ' + startDigit + ' digit.'
});
$("#CHECKFORM").validate({
rules: {
url: "ValidateCreditCard",
}
});
</script>