验证int数据类型asp .net mvc3

Rol*_*sta 1 asp.net data-annotations asp.net-mvc-3

我收到The value 'abc' is not valid for fieldName.错误消息.这是默认的错误消息,我想以更简单的方式覆盖它.
截至目前我所尝试的内容如下所示

  • [RegularExpression(@"^\d+$",ErrorMessage="enter numeric value")]
  • [Integer(ErrorMessageResourceType = typeof(appName.Resources.abc.Resource), ErrorMessageResourceName = "error_numeric")]
  • [RegularExpression("([1-9][0-9]*)")]
  • Range(1,int.max,ErrorMessage="enter numeric value")
    但无法更改默认错误消息.
    建议我做最简单的方法.

       using System;
       using System.Collections.Generic;
       using System.Linq;
       using System.Web;
       using System.ComponentModel.DataAnnotations; 
       using System.Web.Mvc;
    
      namespace blueddPES.ViewModels
         {
         public class ContactViewModel
            {
             [Integer(ErrorMessage="sdfdsf")]
             public int? hp { get; set; }
            }
    
    Run Code Online (Sandbox Code Playgroud)

Rod*_*eek 11

最简单的方法是使用Data Annotations Extensions.它有一些有用的属性,如整数等.

或者您可以自己编写,例如:如何在MVC中通过帮助程序生成时更改"data-val-number"消息验证

编辑:评论后添加完整的样本.

我创建了一个示例vanilla MVC 3项目,然后执行以下操作:

  1. 添加了NuGet包 DataAnnotationsExtensions.MVC3

  2. 添加了一个Model类:

    public class IntegerSample
    {
        [Required(ErrorMessage="Dude, please fill something in!")]
        [Integer(ErrorMessage="Are you stupid? Just fill in numbers only!")]
        public int? TestValue { get; set; }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 添加了家庭控制器:

    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 添加了主页视图:

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>IntegerSample</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.TestValue)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.TestValue)
                @Html.ValidationMessageFor(model => model.TestValue)
            </div>
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
    }
    
    Run Code Online (Sandbox Code Playgroud)

我希望您使用此示例代码获得更多见解.当我运行此示例时,它的工作方式与您希望的一样.

  • 我试过这个,但它对我不起作用.显示默认错误消息 (3认同)
  • 我收到默认错误消息,"每个案例的值'abc'对fieldName"无效. (2认同)