0

我有一个复选框 -HasRaffle需要一个文本框 -RaffleItem如果选中则包含数据HasRaffle。我该怎么做?我以前从未做过自己的 jQuery 验证。这是我尝试过的,但它根本不起作用。我什至接近吗?

$("#donationEventForm").validate({
    rules: {
        RaffleItem: {
            required: function () {
                if ($("#HasRaffle").is(":checked")) {
                    if ($("#RaffleItem").val === '') {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            },
            messages: {
                required: "This is a test!!"
            }
        }
    }
});

编辑:这是我的看法

 @using (Html.BeginForm("Create", "DonationEvent", FormMethod.Post, new {id = "donationEventForm"})) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(false)

    <div class="form-field">
        @Html.LabelFor(model => model.Charity)
        @Html.TextBoxFor(model => model.Charity)
        @Html.ValidationMessageFor(model => model.Charity)
    </div>

    <div class="form-field">
        @Html.LabelFor(model => model.StartDate)
        @Html.TextBoxFor(model => model.StartDate, new {@class = "datepicker"})
        @Html.ValidationMessageFor(model => model.StartDate)
    </div>

    <div class="form-field">
        @Html.LabelFor(model => model.EndDate)
        @Html.TextBoxFor(m => m.EndDate, new {@class = "datepicker"})
        @Html.ValidationMessageFor(model => model.EndDate)
    </div>

    <div class="form-field">
        @Html.Label("Raffle?")
        @Html.CheckBox("HasRaffle", true)
    </div>

    <div class="form-field">
        @Html.LabelFor(model => model.RaffleItem)
        @Html.TextBoxFor(model => model.RaffleItem)
        @Html.ValidationMessageFor(model => model.RaffleItem)
    </div>

    @Html.TextBoxFor(model => model.GLCode, new {@type = "hidden"})
    @Html.TextBoxFor(model => model.TransactionDescription, new {@type = "hidden"})
    @Html.TextBoxFor(model => model.CreatedBy, new {@type = "hidden"})

    <div class="form-field-buttons">
        <input type="submit" value="Create" />
        <input type="button" value="Cancel" onclick="location.href='../Home/Index'"/>
    </div>

}
4

1 回答 1

2

您需要使用 addMethod 添加自定义规则

jQuery.validator.addMethod('checkRaffle', function(value, element){
    if ($("#HasRaffle").is(":checked")) {
        if (value === '') {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}, 'Please write something')

然后规则看起来像这样:

rules: {
    'RaffleItem': {
        'checkRaffle' : true
    }
}

此代码未经测试(并且可能无法工作,因为我看不到您的 DOM),但是如果您可以看到我的代码背后的逻辑,您可能可以调试您的!

于 2013-05-08T19:51:36.333 回答