Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply bootstrap v4 form input validation classes with the ASP.NET Razor syntax?

The following code:

View:(is-valid)

<div class="form-group">
    @Html.LabelFor(m => m.Telefone, new { @class = "font-weight-bold" })
    @Html.TextBoxFor(m => m.Telefone, new { @class = "form-control is-valid", @placeholder = "Digite seu telefone" })
    @Html.ValidationMessageFor(m => m.Telefone, "", new { @class = "text-danger" })
</div>

View:(is-invalid)

<div class="form-group">
    @Html.LabelFor(m => m.Telefone, new { @class = "font-weight-bold" })
    @Html.TextBoxFor(m => m.Telefone, new { @class = "form-control is-invalid", @placeholder = "Digite seu telefone" })
    @Html.ValidationMessageFor(m => m.Telefone, "", new { @class = "text-danger" })
</div>

Example: https://getbootstrap.com/docs/4.3/components/forms/#server-side

Any solution ?

like image 348
Matheus Miranda Avatar asked Jan 27 '18 16:01

Matheus Miranda


People also ask

How can use bootstrap style validation in asp net core?

You can place the above code snippet in the _ValidationScriptsPartial. cshtml file. And now if you run your application, you will be able to see the Bootstrap validation style messages. This way you can customize the ASP.NET Core MVC validation display using JQuery validation control configuration.

How does ValidationMessageFor work in MVC?

ASP.NET MVC: ValidationMessageFor ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. Visit MSDN to know all the overloads of ValidationMessageFor() method.

How do you validate a form in HTML?

Mainly there are two ways to perform HTML form validation. The first is using the built-in functionality provided in HTML5, and the second is by using JavaScript. Using the first method, we don't need to write extra code.


2 Answers

Simple solution by using Tag Helpers:

        <div class="form-group">
            <input asp-for="Email" class="form-control">
            <div class="invalid-feedback" style="display:block;">
                <span asp-validation-for="Email"></span>
            </div>
        </div>
like image 111
Sergey Zykov Avatar answered Nov 05 '22 16:11

Sergey Zykov


The class name is hardcoded: https://github.com/dotnet/aspnetcore/blob/v3.1.6/src/Mvc/Mvc.ViewFeatures/src/HtmlHelper.cs#L25

The only option is to alter CSS.

When you build Bootstrap from sources you can just add the next code into your SCSS file:

.input-validation-error {
  @extend .is-invalid;
}

This will create an alias for existing .is-invalid.

like image 37
Seagull Avatar answered Nov 05 '22 15:11

Seagull