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; }
            }
    
3
  • 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: stackoverflow.com/questions/9921067/…. 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. Commented Mar 30, 2012 at 7: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. Commented Mar 30, 2012 at 8:39
  • yes, you have that option indeed. Commented Mar 30, 2012 at 8:40

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Did you first install the nuget package for the DataAnnotations package? see: nuget.org/packages/DataAnnotationsExtensions.MVC3
What doesn't work then? Do you get an error message or? Please post some more code...
i got default error message which is "The value 'abc' is not valid for fieldName" on every case .
I understand, please post some more code, f.i. your model with the properties where we're talking about..
i tried this but it doesn't work for me. Shows default error message
|
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.

2 Comments

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.
No, I don't have another approach. Personally I use a custom model binder to handle this scenario.
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.

3 Comments

is the link provided by you is relevant?
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.