ValidationMessageFor一直返回错误

时间:2016-02-22 08:41:35

标签: asp.net-mvc

我正在使用jquery验证脚本,此外,我在服务器端创建验证。出于某种原因,即使正确定义了文本字段值,我也始终从服务器获得错误消息。

这是我的观点文件:

 @model StudentsManagment.Models.student
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal" id="studentForm">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.LabelFor(model => model.First_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">            
                @Html.TextBoxFor(model => model.First_name,new {@class = "form-control", name = "First_name" })
                @Html.ValidationMessageFor(model => model.First_name)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Last_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Last_name, new { @class = "form-control", name = "Last_name" })
                @Html.ValidationMessageFor(model => model.Last_name)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Date_of_birth, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Date_of_birth, null,new { @placeholder = "Date: MM-DD-yyyy",@class = "form-control", name = "Date_of_birth" })
                @Html.ValidationMessageFor(model => model.Date_of_birth)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Student_id, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Student_id, new { @class = "form-control", name = "Student_id" })
                @Html.ValidationMessageFor(model => model.Student_id)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.City,new { @class = "form-control", id = "citySearch" , name = "City" })
                @Html.ValidationMessageFor(model => model.City)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.Description,8,1, new { @class = "form-control",name = "Description" })
                @Html.ValidationMessageFor(model => model.Description)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-9 col-md-offset-3">
                <div id="messages"></div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('#studentForm').bootstrapValidator({
            container: '#messages',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                First_name: {
                    validators: {                        
                        notEmpty: {
                            message: 'The first name is required and cannot be empty'
                        },
                        stringLength: {
                            max: 20,
                            min:2,
                            message: 'The full name must be between 2-20 characters'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z\s]+$/i,
                            message: 'The full name can consist of alphabetical english characters and spaces only'
                        }


                    }
                },
                Last_name: {
                    validators: {
                        notEmpty: {
                            message: 'The last name is required and cannot be empty'
                        },
                        stringLength: {
                            max: 20,
                            min: 2,
                            message: 'The full name must be between 2-20 characters'
                        },
                        regexp: {
                            regexp: /^[a-zA-Z\s]+$/i,
                            message: 'The full name can consist of alphabetical english characters and spaces only'
                        }
                    }
                },
                Date_of_birth: {
                    validators: {
                        notEmpty: {
                            message: 'The birth date is required and cannot be empty'
                        },
                        date: {
                            message: 'The date is not valid',
                            format: 'MM-DD-YYYY'                           
                        }
                    }
                },
                Student_id: {
                    validators:{
                        notEmpty: {
                            message: 'The Student id is required and cannot be empty'
                        },
                        regexp: {
                            regexp: /^[0-9\b]+$/,
                            message: 'The student id should conatin only digits'
                        },
                        stringLength: {
                            max: 9,
                            min: 9,
                            message: 'The student id  must be 9 digits'
                        }
                    }                    
                },
                Description: {
                    validators: {                                               
                        stringLength: {
                            max: 1000,                         
                            message: 'The description field should be less than 1000 characters '
                        }
                    }
                }

            }
        });
    });

</script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#citySearch").autocomplete({
            source: function(request,response) {
                $.ajax({
                    url: "/Home/AutoCompleteCountry",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.CityName,
                                value: item.CityName
                            };
                        }))

                    }
                })
            },
            messages: {
                noResults: "No Results was found",
                results: function (resultCount) {
                    return resultCount + (resultCount > 1 ? ' results' : ' result ') + ' found';
                }
            }
        });
    })
</script>

这是我的模特:

    //------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace StudentsManagment.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public  class student
    {

        public int Id { get; set; }
        [Required(ErrorMessage ="First name field is required")]
        [RegularExpression(@"^[a-zA-Z\s]+$")]
        [Range(2, 20)]
        public string First_name { get; set; }

        [Required(ErrorMessage = "Last name field is required")]
        [RegularExpression(@"^[a-zA-Z\s]+$")]
        [Range(2, 20)]
        public string Last_name { get; set; }

        [Required(ErrorMessage = "Birth date field is required")]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
        public System.DateTime Date_of_birth { get; set; }

        [Required(ErrorMessage = "Student id field is required")]
        [RegularExpression(@"^[0-9\b]+$")]
        [StringLength(9)]
        public string Student_id { get; set; }
        public string City { get; set; }
        [StringLength(1000)]
        public string Description { get; set; }
    }
}

控制器功能是:

 [HttpPost]
    public ActionResult Create(student studentToCreate)
    {
        if (!ModelState.IsValid)
        {
            return View();
        }          
        _db.students.Add(studentToCreate);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }

我发现问题出在我的_Layout.cshtml文件中,出于某些原因,当我删除这些行时它没有给我错误:

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>

但是现在我点击“创建”后出现以下错误: enter image description here

2 个答案:

答案 0 :(得分:1)

尝试从firstname和LastName

中删除正则表达式

答案 1 :(得分:1)

在必须在数字字段上使用的字段上删除 RangeAttribute ; - )

如果你想控制长度使用正确的

MSDN - StringLengthAttribute