0

I am coding an MVC 5 internet application and I have a question in regards to validation on a field in a view model.

Here is my view model field:

[Display(Name = "Latitude")]
[Required(ErrorMessage = "Please enter a valid latitude.")]
public double startupLatitude { get; set; }

Here is my view code:

<div class="form-group">
    @Html.LabelFor(model => model.startupLatitude, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.startupLatitude, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.startupLatitude, "" , new { @class = "text-danger" })
    </div>
</div>

If I enter a value that is not a double, such as the following:

Test

I am getting the following validation message displayed in the view:

The value 'Test' is not valid for Latitude.

Instead of:

Please enter a valid latitude.

Why is this?

Thanks in advance.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • Add the html generated by the `@Html.EditorFor()` method –  Dec 03 '14 at 06:26
  • this behaviour is normal and valid because you are entering string whereas model property is of type double. – Kartikeya Khosla Dec 03 '14 at 06:27
  • And the use of `Required` is pointless here because `double` must always have a value. It's only necessary if you have `double?` (nullable) –  Dec 03 '14 at 06:31

1 Answers1

1

Because the Required parameter check for not null and the data you have entered is a "String" where as it expects double

If you will keep the field blank then the error Message will be shown as "Please enter a valid latitude."

Edit :

Set Default/Replace Default Validation Message

Or

Try Using Regular Expression as well.

Community
  • 1
  • 1
Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51
  • Can I modify the code some way so that the validation message will be the same for either a null entry or a string? – Simon Dec 03 '14 at 06:32
  • 1
    `DataType` does not contain a enum value for `Double` –  Dec 03 '14 at 06:50