This is a problem I ran into when converting my Bootstrap 3 based site to MDB which is based on Bootstrap 4.

The validation class in MDB is is-invalid as opposed to input-validation-error. I think it’s because of Bootstrap as opposed to MDB itself. But, in any case I had to change it with minimal code.

One solution is given here.

Adding the @Html.FieldHasError(m => m.Password) in the class attribute of every input seems to be too much work. So, here is my solution that uses TagHelper instead of extension methods on IHtmlHelper.

[HtmlTargetElement("input", Attributes = "md-for", TagStructure = TagStructure.WithoutEndTag)]
public class MdInputTagHelper : InputTagHelper
{
    public MdInputTagHelper(IHtmlGenerator generator)
        : base(generator)
    {
    }

    [HtmlAttributeName("md-for")]
    public ModelExpression MdFor 
    {
        get => For;
        set => For = value;
    } 

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        base.Process(context, output);

        var fullName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, For.Name);

        if (ViewContext.ViewData.ModelState.TryGetValue(fullName, out var entry) && entry.Errors.Count > 0)
        {
            output.AddClass("is-invalid", HtmlEncoder.Default);
            output.RemoveClass("input-validation-error", HtmlEncoder.Default);
        }
    }
}

Now, to use the class invalid-feedback in your inputs you have to do a single change, replace asp-for in the input tag with md-for.

<div class="md-form">
    <i class="fas fa-envelope prefix"></i>
    <input md-for="Input.Email" class="form-control">
    <label asp-for="Input.Email">Your email</label>
    <span class="invalid-feedback" asp-validation-for="Input.Email"></span>
</div>

One last thing, remember to import the tag helper in your _ViewImports.cshtml file:-

@addTagHelper Maxotek.WebAppUtils.Helpers.MdInputTagHelper, Maxotek.WebAppUtils
No votes yet.
Please wait...