I want to validate in my text box only numbers (integers or double/float) in create/edit views. But there's a problem. If I write only numbers it works good. If I write only letters it works good (it appear the default error message: "must be a number").
But If I write a number and then letters (for example: 3333aaa) it don't appear the validation message "must be a number". The controller works good, since it don't pass ModelState.isValid, but I don't know why the validation message don't detect the letters after numbers.
The form is by default (since I use entity framework for models and the controllers/views are automatically generated). Here is the field in the model:
[Required]
[DisplayName("Number 1")]
[DisplayFormat(DataFormatString = "{0:c}")]
public Nullable<double> Importe_nom { get; set; }
And here the .cshtml:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.Importe_nom, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Importe_nom, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Importe_nom, "", new { @class = "text-danger" })
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</div>
}
The only change I made is a method in javascript for decimals:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$.validator.methods.number = function (value, element) {
value = floatValue(value);
return this.optional(element) || !isNaN(value);
}
$.validator.methods.range = function (value, element, param) {
value = floatValue(value);
return this.optional(element) || (value >= param[0] && value <= param[1]);
}
function floatValue(value) {
return parseFloat(value.replace(",", "."));
}
</script>
}
But that error is not for the script. If I delete it, the error continues.
The ModelState.isValid == false:
The error message: