MVC 5 model validation message not correctly displaying

2.1k views Asked by At

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.

1

There are 1 answers

2
Arijit Mukherjee On

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.