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());
}
});