Question

I'm implementing a donation form and I have a Donation model with the field "Amount":

[Required]
[DataMember(IsRequired = true)]
[Range(36, 10000)]
public decimal Amount { get; set; }

I also have it's validation set in the view:

<div class="editor-label">
    @Html.LabelFor(model => model.Payment.Amount)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Payment.Amount)
    @Html.ValidationMessageFor(model => model.Payment.Amount)
</div>

Problem is that when the user selects a diffrent "Currency" in the webpage the minimum amount should be changed for some currencies.

What I tried to do is to change the Input attributes:

$("#Donation_Currency").change(function () {
    var curr = this.value;
    switch (curr) {
        case "USD":
            document.getElementById("Donation_Amount").setAttribute("data-val-range", "The field Amount must be between 36 and 10000.");
            document.getElementById("Donation_Amount").setAttribute("data-val-range-min", "36");
            break;
        case "ILS":
            document.getElementById("Donation_Amount").setAttribute("data-val-range", "The field Amount must be between 100 and 10000.");
            document.getElementById("Donation_Amount").setAttribute("data-val-range-min", "100");
            break;
        default:
    }
});

But even though I see that the input attributes changed I still see the old message appears.

I'm doing something wrong that's for sure but the question is:

How do I change the validation of the field according to the value set in another field?

Was it helpful?

Solution

Quote OP:

"But even though I see that the input attributes changed I still see the old message appears."

That's because once the plugin is initialized, you cannot simply change the jQuery Validate options by changing HTML attributes (as you've learned). Plugin initialization occurs once on page load and never again.

After initialization, you must use methods provided by the plugin to make dynamic changes to rules. See the .rules('add') method which dynamically adds rule(s)… it will also over-ride a previously defined rule.

Try something more like this…

$("#Donation_Currency").change(function () {
    var curr = this.value;
    switch (curr) {
        case "USD":
            $("#Donation_Amount").rules('add', {
                range: [36,10000],
                messages: {
                    range: "The field Amount must be between 36 and 10000."
                }
            });
            break;
        case "ILS":
            $("#Donation_Amount").rules('add', {
                range: [100,10000],
                messages: {
                    range: "The field Amount must be between 100 and 10000."
                }
            });
            break;
        default:
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top