Mariusz Jamro Mariusz Jamro - 2 months ago 11
C# Question

How to check in razor view if field is valid in ASP.NET Core MVC

I use bootstrap with ASP.NET Core and to indicate form field validation errors i want to add

has-errors
class to
form-group
div when given field has an error. The view looks like that:

<div class="form-group">
<label asp-for="Fragment.Content" class="col-lg-2 control-label "></label>
<div class="col-lg-10">
<textarea asp-for="Fragment.Content" class="form-control content-editor"></textarea>
<span class="help-block">A longer block of help text that breaks onto a new line and may extend beyond one line.</span>
<span asp-validation-for="Fragment.Content"></span>
</div>
</div>


I would like to do something like:

<div class="form-group" asp-add-class-if-error="has-errors" for-field="Fragment.Content"/>


I know i can write my own tag helper, however i am curious if there is a built-in solution.

Answer

I found that you can use:

@using Microsoft.AspNetCore.Mvc.ModelBinding

@if(ViewData.ModelState.GetFieldValidationState("Fragment.Content") == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
{
    //  something here
}