【问题标题】:MVC Validation does not seem to work for text fields but is fine with numeric fieldsMVC 验证似乎不适用于文本字段,但适用于数字字段
【发布时间】:2021-11-18 19:31:16
【问题描述】:

我的模型验证似乎有问题。 “标题”字段验证似乎不起作用,而“价格”验证似乎工作正常。 此外,在其他页面上,验证似乎在文本字段上正常工作,只是这个页面我遇到了问题。看它太久了,所以我真的很感激任何帮助。

我的模特

public class Product
    {
        public int Id { get; set; }
        
        [Required(ErrorMessage = "This is Required Field")]
        public string Title { get; set; }
        
        public string Color { get; set; }
        
       
        [Required(ErrorMessage = "This is Required Field")]
        public decimal Price { get; set; }

    }

观点

    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td>
                    <label>Title:</label></td>
                <td>@Html.EditorFor(m => m.Title)</td>
                <td>@Html.ValidationMessageFor(m => m.Title)</td>
            </tr>
            <tr>
                <td>
                    <label>Color:</label></td>
                <td>@Html.EditorFor(m => m.Color)</td>
                <td>@Html.ValidationMessageFor(m => m.Color)</td>
            </tr>
            <tr>
                <td>
                    <label>Price:</label></td>
                <td>@Html.EditorFor(m => m.Price)</td>
                <td>@Html.ValidationMessageFor(m => m.Price)</td>
            </tr>
        </table>
        <button type="submit">Submit</button>
}

行动

[HttpPost]
        public ActionResult Add(Product model)
        {
            if(ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }
            return View(model);
        }

我在 web.config 文件中将 ClientValidationEnabled 和 UnobtrusiveJavaScriptEnabled 设置为 true。

我的头文件里也有以下内容

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

【问题讨论】:

    标签: asp.net-mvc unobtrusive-validation


    【解决方案1】:

    尝试添加验证摘要

     @using (Html.BeginForm())
    {
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    .....
    }
    

    并且由于十进制不可为空,默认为 0,因此 reqiered 将不起作用,因为它不为空。因为是价格字段,试试这个,它是用于货币的

    [DataType(DataType.Currency)]
    [RegularExpression(@"^\d+.?\d{0,2}$", ErrorMessage = "Wrong format")]
    public decimal Price { get; set; }
    

    【讨论】:

    • 对不起@Serge,但它没有用。如果留空,标题字段仍然拒绝验证
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多