0

I have a form with shipping and billing information using a view model containing some required attributes.

Here's an exctract of the code enough to explain the issue.

Extract of the view model:

public class CheckoutViewModel
{
    [Required]
    public string ShippingPostalCode { get; set; }

    [Required(ErrorMessage = "*")]
    public string BillingPostalCode { get; set; }
}

Extract of the razor form:

@Html.TextBoxFor(m => m.ShippingPostalCode, new { @class = "form-control", placeholder = "Postal code" })
@Html.TextBoxFor(m => m.BillingPostalCode, new { @class = "form-control", placeholder = "Postal code", data_bind = "attr: { 'readonly': billingSameAsShipping }" }) @Html.ValidationMessageFor(model => model.BillingPostalCode)

I use Knockout to make the billing fields (including BillingPostalCode) readonly if a checkbox is checked using the observable billingSameAsShipping variable.

<input type="checkbox" data-bind="checked: billingSameAsShipping" id="billingSameAsShippingCheckbox" />

If the checkbox is not checked, and the BillingPostalCode is left empty, the validation fires correctly. However, if BillingPostalCode is empty but the checkbox is checked, making the field readonly, the validation is not fired and the ModelState's IsValid is having the value true.

Any clues if this expected behaviour, or ideas how to work around it?

Any help is appreciated. Thanks.

Edit: I added the JavaScript code if it helps.

var shipping = {
    billingSameAsShipping: ko.observable(false)
};
ko.applyBindings(shipping);

$("#billingSameAsShippingCheckbox").on("change", function () {
    if (this.checked) {
        $("#BillingPostalCode").val($("#ShippingPostalCode").val());
    }
});
Marc Annous
  • 417
  • 5
  • 13
  • Disabled(readonly) checkbox wont post values to the server. There are many workarounds mentioned in this link that should help you: http://stackoverflow.com/questions/4727974/how-to-post-submit-an-input-checkbox-that-is-disabled – Boney Nov 13 '16 at 12:46
  • Can you post your Knockout code ? – Yanga Nov 13 '16 at 13:48
  • Disabled fields don't get posted but readonly are posting fine. Also the model state is valid. The problem is only with the client side validation. – Marc Annous Nov 13 '16 at 16:16
  • Use hidden field -> @Html.HiddenFor(x=> x.BillingPostalCode) – Ridikk12 Nov 13 '16 at 16:19
  • @Yanga here's the concerned Knockout code. var shipping = { billingSameAsShipping: ko.observable(false) }; ko.applyBindings(shipping); $("#billingSameAsShippingCheckbox").on("change", function () { if (this.checked) { $("#BillingPostalCode").val($("#ShippingPostalCode").val()); } }); – Marc Annous Nov 13 '16 at 16:19

1 Answers1

0

It seems that the jQuery validator that it uses ignores readonly inputs. I managed to fix it with this.

$.validator.setDefaults({ ignore: null });
Marc Annous
  • 417
  • 5
  • 13