Reputation: 3492
How to add required field validation on client side with custom message for Radio Button in ASP.Net MVC ?
<div class="form-group">
<div class="col-sm-4 control-label">
<label class="hthin" asp-for="IsGuidance"></label>
<label class="hthin">Coach: @Model.GuideName</label>
</div>
<div class="col-sm-3 checkbox-inline">
@Html.RadioButtonFor(model => model.IsGuidance, 1, new { @Id = "IsGuidanceYes" })
<label class="hthin" for="IsGuidanceYes">Yes</label>
@Html.RadioButtonFor(model => model.IsGuidance, 0, new { @Id = "IsGuidanceNo" })
<label class="hthin" for="IsGuidanceNo">No</label>
<span asp-validation-for="IsGuidance" class="text-danger"></span>
</div>
</div>
I wrote a Jquery file :
$('input[name="IsGuidance"]').rules("add",
{
required: true,
messages: {
required: "Please select Yes or No"
}
});
Though, this is not validating (or) validation message is not showing on the UI.
Upvotes: 0
Views: 1637
Reputation: 24957
I tested in this fiddle and your client-side validation rule seem to be working fine. What you should do is place custom error message using either errorPlacement
or errorElement
with errorContainer
inside validate()
function:
jQuery (inside $(document).ready()
)
// hint: you can use $('form') selector
// using errorPlacement
$('#form').validate({
errorPlacement: function (error, element) {
error.appendTo($('#errorPlaceholderName'));
}
});
// alternative with errorElement & errorLabelContainer
$('#form').validate({
errorElement: 'span',
errorLabelContainer: '.text-danger'
});
You may also try putting server-side viewmodel property validation attribute:
Model
[Required(ErrorMessage = "IsGuidance is required")]
public int? IsGuidance { get; set; }
Note: rules('add', ...)
method must follows validate()
in order to enable client-side validation, as given in similar issue.
Reference: jQuery validation plugin
Upvotes: 1
Reputation: 66
For client side validation to work automatically in Asp.Net MVC, you need to follow certain steps i.e
1 - Decorate your viewmodel property with the DataAnnotationAttribute which you do for server side validation anyway.
2 - Verify that your client side validation is enabled. you can refer this video on different ways to enable client side validation. By the way, by default it is always enabled: https://www.youtube.com/watch?v=PLe7WbsuHPU
3 - Make sure these 3 jQuery libraries are referenced in your page in the order shown below : jquery.js, jquery.validate.js and jquery.validate.unobtrusive.js.
4 - Use @Html.BeginForm helper method for form and place all your form fields within it. All form fields should also be generated using appropriate @Html helper methods.
That's all and client side validation should work when you submit the form.
In your case for custom message, Decorate your data annotation attribute with custom error message for displaying custom error message like
class ViewModel
{
[Required(ErrorMessage ="Custom error message")]
public bool IsGuidance{get;set;}
}
Upvotes: 0