My form includes fields for street address, street address line 2, city, state/province, zip code, and country. I'm having trouble validating the error message upon leaving the form.
I attempted to use [Required(ErrorMessage="Field is required")] on the Model, but it wasn't successful. The goal is to highlight all mentioned fields in red, and when leaving the State/Province field, validate with the error message "Field is required". Below is my current attempt at achieving this in the code:
// Model class
[Required(ErrorMessage = "This field is required")]
public string State { get; set; }
View.cshtml
<div class="row">
<label for="Address">Address</label>
<div class="col-md-6 ">
<div class="input-group pull-right">
@Html.TextBoxFor(m => m.HomeMainModel.Address, new { @class = "form-control", type = "text", id = "inputFormVal",autofocus = "autofocus", placeholder = "Street Address", required = "required" })
<div class="input-group-append">
<div class="input-group-text">
</div>
</div>
</div>
</div>
<div class="col-md-6">
<label id="labelMessageBx" class="text-danger" style="display:none"></label>
</div>
</div>
...
// function for validating city, street address, street_address_line2, and state_province fields when leaving.
$(function() {
$('#inputFormVal').blur(function() {
var city = document.getElementById("inputFormVal").value;
var expr = /^([\w-\.]+)@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(city)) {
document.getElementById("labelMessageBx").style.display = "inline";
} else {
document.getElementById("labelMessageBx").style.display = "none";
}
});
});