1

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:

enter image description here

The error message:

enter image description here

Keras-JOB
  • 109
  • 10
  • Please don't use jQuery anymore - it's 2021. jQuery stopped being relevant at least 7-8 years ago. – Dai May 14 '21 at 09:10
  • What `CultureInfo` are you using? Have you considered using `[RegularExpression("...")]` to validate instead? Please edit your post to show the **full contents** of `ModelState` when it's `IsValid == false` when you pass-in `333aaa`. – Dai May 14 '21 at 09:11
  • Why is the property typed as `Nullable` when it's also is marked as `[Required]`? If you use a non-`Nullable` type then `[Required]` is implicit _and_ it helps avoid a slew of input validation issues which I think may be involved here. – Dai May 14 '21 at 09:12
  • Is nullable because the previous version of the DB there are null values. But the news one will not be more nulls. CultureInfo is the default in the project, I don't change anything. The regular expression sounds good. How can I make a good regular expression for integers/decimal numbers? Thanks – Keras-JOB May 14 '21 at 09:15
  • For Regular Expression, look here: [link](https://stackoverflow.com/questions/273141/regex-for-numbers-only) – Janosch Geigowskoskilu May 14 '21 at 09:18
  • Something like `[RegularExpression(@"^\s*\d+\s*$")]` will validate unsigned integers (while also accepting outer whitespace if the user was sloppy with the clipboard), and `[RegularExpression(@"^\s*\d+\.?\d*")]` will accept English-style decimal numbers (but won't accept digit grouping with commas nor European-style decimal numbers). That said, I think there's a better way but it's 2am right now and I can't remember. – Dai May 14 '21 at 09:19
  • Thanks for your help. I updated the modelstate.isvalid==false. The people who will use the application will write the decimals with commas. So I need a validation for numbers and comas for decimals – Keras-JOB May 14 '21 at 09:23
  • @Keras-JOB Thank you for posting the `ModelState`, but you're only showing `RawValue` - please show the `Errors` collection. – Dai May 14 '21 at 09:23
  • I upload it. It says: "value 333aaa is not valid for Importe_nom" – Keras-JOB May 14 '21 at 09:28
  • Ok I use the regular expression: [RegularExpression(@"^\s*\d+\,?\d*")] (I change . for ,) And now it work. And the javascript will change the comma for dot. But I'm still curious why the default validation don't show the message when I write 33aa – Keras-JOB May 14 '21 at 09:42
  • @Keras-JOB Yeah, that's confusing because _it should_. But I think the problem is caused by your use of `Nullable` instead of just `double`. – Dai May 15 '21 at 15:46

0 Answers0