0

I am using DataAnnotations for Validation in MVC 4.0 and I have a property as follows:

 [Range(typeof(Decimal), "0.001", "9999", ErrorMessage = "Exchange rate must be a number between {1} and {2}.")]

The message I get is "The field Exchange rate must be a number between ..."

I want to get rid of the words "The field". What is easiest possible way to do achieve teh goal?

chugh97
  • 9,602
  • 25
  • 89
  • 136

1 Answers1

1

The following worked for me. I received the message "Exchange rate must be a number between 0.001 and 9999". It would have been helpful if you posted how you structured your model class.

C#

using System.ComponentModel.DataAnnotations;

// ...

public class Foo
{
    [Range(typeof(Decimal), "0.001", "9999", ErrorMessage = "Exchange rate must be a number between {1} and {2}.")]
    [RegularExpression(@"\d+?(?:\.\d{3,3})?", ErrorMessage="Exchange rate must be a number.")]
    [Required(ErrorMessage = "Exchange rate is required.")]
    public decimal ExchangeRate { get; set; }
}

View

@model WebApplication2.Models.Foo

@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.ExchangeRate)<br />
    @Html.TextBoxFor(model => model.ExchangeRate)<br />
    @Html.ValidationMessageFor(model => model.ExchangeRate)<br />
    <button type="submit">Submit</button>
}

@section scripts
{
    @* Assuming bundle is jqueryval *@
    @Scripts.Render("~/bundles/jqueryval")
}

Controller

public ActionResult Test()
{
    return View(new Foo());
}

[HttpPost]
[ActionName("Test")]
public ActionResult TestConfirmed(Foo foo)
{
    // NOTE: You would need additional logic for dealing with the ModelState.IsValid
    //       This is for illustration purposes only
    return View(foo);
}
Mario J Vargas
  • 1,185
  • 6
  • 12
  • Hmmm... That's an indication that you are hitting a different type of validator. Your post should have indicated that (i.e. what values you were inputting that triggered the "wrong" validation message). In that case, when I tried your example input value (dh67), I got a different validation message, "The field ExchangeRate must be a number." You can try a regular expression validator or a custom validator. – Mario J Vargas Jun 02 '14 at 18:58
  • Alternatively, you can decorate the `ExchangeRate` with the `Display` or `DisplayName` attributes so it reads "Exchange Rate" instead of the property name "ExchangeRate". – Mario J Vargas Jun 02 '14 at 19:05
  • Sorry I didn't mention that but I get "The field ExchangeRate must be a number.". How can I get rid of the words the field... – chugh97 Jun 05 '14 at 16:19
  • No problem. See my updated post. I added a `RegularExpression` and `Required` attribute. These two, along with the `Range` attribute help cover your scenarios: no value passed, value out of range, value not a number. Feel free to revise the Regex since it's very basic and I didn't take the time to examine all possibilities. – Mario J Vargas Jun 05 '14 at 18:31