Validation on int data type asp .net mvc3

2020-07-27 19:45发布

问题:

I am getting The value 'abc' is not valid for fieldName. as error message. which is default error message and i want to override it in easier way.
as of now what i have tried is listed below

  • [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")
    but failed to change default error message.
    Suggest me the easiest possible way to do this.

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

回答1:

Easiest way is to use Data Annotations Extensions. It has some useful attributes for things like Integers, etc.

Or you could write your own, like in: How to change 'data-val-number' message validation in MVC while it generate by helper

Edit: Added complete sample after comments.

I created a sample vanilla MVC 3 project and then did the following:

  1. Added NuGet package DataAnnotationsExtensions.MVC3

  2. Added a Model class:

    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; }
    }
    
  3. Added a Home Controller:

    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
    }
    
  4. Added a Home View:

    @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>
    }
    

I hope you get some more insights using this sample code. When I run this sample, it works just as you'd want to expect.



回答2:

You could implement a custom model binder as shown here or use a string datatype instead of integer and then apply the regular expression data annotation. Of course if you use a string datatype you might need to parse this string manually to the underlying datatype when mapping your view model to a domain model.



回答3:

We use an extended version of Phil Haack MetadataProvider which can do localization.

Take at look at this blog article: http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx

In summary:

  • It determines a resource key by using the class type + property, e.g. Person_FirstName
  • It looks up error messages by suffixing the validation property, e.g. Person_FirstName_Required
  • You just supply the resource file with those entries.