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

和自甴很熟 提交于 2020-06-09 18:22:09

问题


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 ?


回答1:


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>



回答2:


//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);
        }
    },
});



回答3:


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';



回答4:


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



来源:https://stackoverflow.com/questions/48477738/how-to-apply-bootstrap-v4-form-input-validation-classes-with-the-asp-net-razor-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!