1

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; }
            }
    
RollerCosta
  • 5,020
  • 9
  • 53
  • 71
  • 1
    Don't look for a data annotation to cover this validation scenario. You won't be able to achieve that with value types such as integers as I already answered in a previous question of yours: http://stackoverflow.com/questions/9921067/server-side-validation-of-int-datatypec-asp-net-mvc3. You need a custom model binder because it is the default model binder that is parsing the request value into an integer and if it fails it adds a default error message which is hardcoded as a resource in the System.Web.Mvc assembly. – Darin Dimitrov Mar 30 '12 at 07:03
  • but @DarinDimitrov i dont want to add that much of custom code for this small thing. Instead of adding custom modelbinder i have another option to take string as data type instead of int. – RollerCosta Mar 30 '12 at 08:39
  • yes, you have that option indeed. – Darin Dimitrov Mar 30 '12 at 08:40

3 Answers3

10

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.

Community
  • 1
  • 1
Rody
  • 2,675
  • 1
  • 22
  • 40
  • Did you first install the nuget package for the DataAnnotations package? see: http://nuget.org/packages/DataAnnotationsExtensions.MVC3 – Rody Mar 30 '12 at 05:51
  • What doesn't work then? Do you get an error message or? Please post some more code... – Rody Mar 30 '12 at 05:55
  • 2
    i got default error message which is "The value 'abc' is not valid for fieldName" on every case . – RollerCosta Mar 30 '12 at 06:32
  • I understand, please post some more code, f.i. your model with the properties where we're talking about.. – Rody Mar 30 '12 at 06:35
  • Check my edit, updated the post with sample (only code highlighting is a bit messy) – Rody Mar 30 '12 at 09:19
  • 3
    i tried this but it doesn't work for me. Shows default error message – RollerCosta Apr 10 '12 at 11:32
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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • done with string part and its working fine. But still i need a better approach(apart from ModelBinder). If u gt something then please let me know. – RollerCosta Mar 30 '12 at 08:50
  • No, I don't have another approach. Personally I use a custom model binder to handle this scenario. – Darin Dimitrov Mar 30 '12 at 08:51
0

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.
Alex Duggleby
  • 7,948
  • 5
  • 37
  • 44
  • is the link provided by you is relevant? – RollerCosta Mar 30 '12 at 06:38
  • I think so, if you want to change the default message that data annotations uses, you can do it by putting them in the resource file (which is best practice for localized strings anyway) by using the provider available in that post. – Alex Duggleby Mar 30 '12 at 08:00
  • presently i am using resource file to get everything from it . by saying everything i mean display name ,error message(everyhting displayed on view), and i am also getting it , but the problem is with only int data type error message. – RollerCosta Mar 30 '12 at 08:52