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

7

8

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 ?

Pauiie answered 27/1, 2018 at 16:14 Comment(1)
S
10

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.

Sung answered 15/10, 2020 at 1:50 Comment(1)
For those searching, this works with .NET 5 and Bootstrap 5.Padraic
M
8

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>
Magnesite answered 20/6, 2018 at 17:38 Comment(1)
What if you want to change the Input box itself using the is-vailid or is-invalid so it shows green or red? "<input type="text" class="form-control is-invalid" >"Interlineate
L
0

Razor uses jQuery validation. You only need to hock jq-valid with Bootstrap:

$('form').validate().settings.errorClass += ' is-invalid';
$('form').validate().settings.validClass += ' is-valid';
Liverwurst answered 25/6, 2019 at 9:0 Comment(0)
C
0

I leave here two solutions that have not been mentioned before. One dogmatic and one pragmatic, but depending on what you are looking for both solutions can be interesting. With both you will solve the problem in 1 minute.

Proof of concept:

enter image description here

Brief introduction (really necessary):

Microsoft uses jquery-validation to perform client-side validation, and has extended the functionality of this library with its own jquery-validation-unobtrusive library.

If you go to the wwwroot/lib/jquery-validation-unobtrusive folder within the project you will find that within this library are rules that add classes such as “input-validation-error”.

Solution 1:

If we inspect the uses of, we see that “errorClass” is first queried from the options, and if it does not exist, then “input-validation-error” is used by default.

enter image description here

The first solution is to generate the configuration in which we are the ones who indicate the name of “errorClass”.

Include the following script in your execution tree:

<script>
    const settings = {
        errorClass: 'is-invalid',
    }
    $.validator.unobtrusive.options = settings
</script>

Good place to do this would be at the end of your _ValidationScriptsPartial.cshtml file. Either way, you have to make sure that your script is executed after the inclusion of the jquery.validate.unobtrusive.js file.

Solution 2:

The solution is as simple as replacing the string “input-validation-error” with “is-invalid” (there are two places).

enter image description here

Why do I consider these solutions to be the cleanest and simplest?

  • There is no need to add Extensions, Helpers or magic Services that you have to rethink later (you always have to adjust the code, or update the .Net version, or include a new dev).

  • This solutions works transparently with any Razor project. The dev should not even notice this tweak. He should just write his Razor components.

  • It does not introduce weird rules with JS, which later in the execution chain can be difficult to debug.

  • It does not set up new styles, nor magic inheritances to solve the problem, which usually causes headaches when styles do not work properly.

  • Finally, this solution not only works for Bootstrap, it works for any stylesheet you want to use. It avoids name dependency with Microsoft defined classes (apparently, without being consistent in this aspect, so I don't see any good reason to keep using them).

Cornel answered 5/6, 2024 at 10:18 Comment(0)
N
-1
//CONFIGURACAO BOOTSTRAP 4 PARA JQUERY VALIDATION PLUGIN
jQuery.validator.setDefaults({
    onfocusout: function (e) {
        this.element(e);
    },
    //onkeyup: false,
    highlight: function (element) {
        jQuery(element).closest('.form-control').addClass('is-invalid');
    },
    unhighlight: function (element) {
        jQuery(element).closest('.form-control').removeClass('is-invalid');
        jQuery(element).closest('.form-control').addClass('is-valid');
    },

    errorElement: 'div',
    errorClass: 'invalid-feedback',
    errorPlacement: function (error, element) {
        if (element.parent('.input-group-prepend').length) {
            $(element).siblings(".invalid-feedback").append(error);
            //error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    },
});
Nicaea answered 10/3, 2020 at 17:5 Comment(1)
verbal explanations are often very helpful in answersCamarillo
F
-1

Building off Seagull's answer for .Net 5 and Bootstrap 5 (I can't comment on his answer).

I was able to follow this guide, https://www.dotnetcatch.com/2019/05/16/adding-bootstrap-sass-to-asp-net-core/, to build a custom Bootstrap CSS that includes the ASP.NET validation class name so that you get the look of the Bootstrap validation controls.

@import "../lib/bootstrap/scss/bootstrap";

.input-validation-error {
    @extend .is-invalid;
}
Ferrick answered 9/11, 2021 at 2:49 Comment(0)
Z
-4

be sure to include : "jquery .js jquery.validate .js jquery.validate.unobtrusive .js"

Zeke answered 25/2, 2018 at 20:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.