MVC 4 client side validation not working

后端 未结 21 1270
情话喂你
情话喂你 2020-12-02 14:00

Can anyone tell me why client side validation is not working in my MVC 4 application.

_layout.schtml

@Scripts.Render("~/bundles/jquery")
@R         


        
相关标签:
21条回答
  • 2020-12-02 14:43

    I finally solved this issue by including the necessary scripts directly in my .cshtml file, in this order:

    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="/Scripts/jquery.validate.js"></script>
    <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
    

    It's a bit off-topic, but I'm continually amazed by how often this sort of thing happens in Web programming, i.e. everything seems to be in place but some obscure tweak turns out to be necessary to get things going. Flimsy, flimsy, flimsy.

    0 讨论(0)
  • 2020-12-02 14:43

    this works for me goto your model class and set error message above any prop

    [Required(ErrorMessage ="This is Required Field")]
        public string name { get; set; }
    

    import namespace for Required by Ctrl+. and finally add this in view

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    
    0 讨论(0)
  • 2020-12-02 14:44

    Im my case I added and id equals to the name automatically generated for VS on the html and in the code I´ve added a line to that case.

    $(function () {
                $.validator.addMethod('latinos', function (value, element) {
                    return this.optional(element) || /^[a-záéóóúàèìòùäëïöüñ\s]+$/i.test(value);
                });
    
                $("#btn").on("click", function () {
                    //alert("aa");
                    $("#formulario").validate({                    
                        rules:
                        {
                            email: { required: true, email: true, minlength: 8, maxlength: 80 },
                            digitos: { required: true, digits: true, minlength: 2, maxlength: 100 },
                            nombres: { required: true, latinos: true, minlength: 3, maxlength: 50 },
                            NombresUsuario: { required: true, latinos: true, minlength: 3, maxlength: 50 }
                        },
                        messages:
                        {
                            email: {
                                required: 'El campo es requerido', email: 'El formato de email es incorrecto',
                                minlength: 'El mínimo permitido es 8 caracteres', maxlength: 'El máximo permitido son 80 caracteres'
                            },
                            digitos: {
                                required: 'El campo es requerido', digits: 'Sólo se aceptan dígitos',
                                minlength: 'El mínimo permitido es 2 caracteres', maxlength: 'El máximo permitido son 10 caracteres'
                            },
                            nombres: {
                                required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                                minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                            },
                            NombresUsuario: {
                                required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                                minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                            }
                        }
                    });
                });
    
    <tr>@*<div class="form-group">     htmlAttributes: new { @class = "control-label col-md-2" }      , @class = "form-control" }*@
                    <td>@Html.LabelFor(model => model.NombresUsuario )</td>
    
                            @*<div class="col-md-10">*@
                    <td>
                        @Html.EditorFor(model => model.NombresUsuario, new { htmlAttributes = new { id = "NombresUsuario" } })
                        @Html.ValidationMessageFor(model => model.NombresUsuario, "", new { @class = "text-danger" })
                    </td>
    
    0 讨论(0)
  • 2020-12-02 14:46

    I'll like to add to this post, that I was experienceing the same issue but in a PartialView.

    And I needed to add

    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    

    To the partial view, even if already present in the _Layout view.

    References:

    • Data Annotations / Validation not working for partial views
    0 讨论(0)
  • 2020-12-02 14:48

    If you use jquery.validate.js and jquery.validate.unobtrusive.js for validating on client side, you should remember that you have to register any validation attribute of any DOM element on your request. Therefor you can use this code:

    $.validator.unobtrusive.parse('your main element on layout');
    

    to register all validation attributes. You can call this method on (for example) : $(document).ajaxSuccess() or $(document).ready() to register all of them and your validation can be occurred successfully instead of registering all js files on cshtml files.

    0 讨论(0)
  • 2020-12-02 14:48

    In my case the validation itself was working (I could validate an element and retrieve a correct boolean value), but there was no visual output.

    My fault was that I forgot this line @Html.ValidationMessageFor(m => ...)

    The TS has this in his code and got me on the right track, but I put it in here as reference for others.

    0 讨论(0)
提交回复
热议问题