如何在 jQuery 自定义验证器方法中格式化消息

How to format a message in jQuery custom validator method

我正在尝试编写如下自定义方法来使用 jQuery validate 验证信用卡号。

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 信用卡,那么错误信息应该是 please enter a visa card number likely for Master credit card

关于如何传递卡片类型值来格式化消息有什么想法吗?

您可以像下面这样操作:

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>