C# Decimal field accept value equal to or greater than 0 in validation

Asked

Viewed 1,353 times

2

I’m having trouble validating my type fields decimal using Razor, when I try to enter 0 in the field it gives the following error message.

The field XXXX must be a number.

Follow down my class and how I insert the field with Razor

public class ClasseViewModel
{
    [Required(ErrorMessage = "Campo Obrigatorio")]
    [Display(Name = "Campo Decimal")]
    public decimal? CampoDecimal { get; set; }
}

Razor:

@Html.LabelFor(model => model.CampoDecimal, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.CampoDecimal, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CampoDecimal, "", new { @class = "text-danger" })

How would you validate whether the field is numerical or not to accept the value 0.

  • https://stackoverflow.com/questions/7256753/min-max-value-validators-in-asp-net-mvc

  • if it is mandatory, why put a field that may be null ? decimal?

  • in case it is pq it at first comes null, however on this screen he is obliged to inform you

  • I just generated a test just to check it out the way you worked out and I had no problem recording Zero, weird too, this class only has these fields, will it be another field?

  • @Virgilionovic I just did the test on a new project and really passed, it was probably something that they overwritten in the project I’m using, you know where do these validations for me to check if something was overwritten? I believe it may have even been the js file?

  • Look in the Scripts folder has the validation files are they are responsible for such, if you overwrite with that of the new ones one one could test if they really are them!

Show 1 more comment

1 answer

3

Since it’s all Razor, use DataAnnotations to set the limit of 1 even to infinity (may be another number) and remove ? if the parameter is required

[Range(1, Double.PositiveInfinity)]
public decimal CampoDecimal { get; set; }

For more details: data Annotations

  • It doesn’t work, I want to use with the value 0 and I’ve used this validation before and still the previous validation continues

Browser other questions tagged

You are not signed in. Login or sign up in order to post.