Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do not allow negative values in int property MVC C#

Tags:

c#

I do have a strongly typed view in MVC C# in which the user has to enter a int value, the property is

 [Required(ErrorMessage="especificar correlativo")]
    [Display(Name = "Correlativo")]
    [Range(1, 9999, ErrorMessage = "correlativo no valido")]
    [RegularExpression(@"^(((\d{1})*))$", ErrorMessage = "correlativo no valido")]
    public int correlativo1
    {
        get { return Correlativo1; }
        set { Correlativo1 = value; }
    }

but my problem is that when the vies displays, the input lets the user specifies a negative value via the arrows at the right of the input

enter image description here

and yes it shows the validation message

enter image description here

but I don´t want (since the very beggining) let the user to have the option of specifies negative values.

this is the input in the view

<div class="form-group">
                    <div class="col-md-2">
                        @Html.LabelFor(model => model.correlativo1, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.correlativo1, new { htmlAttributes = new { @class = "form-control left-border-none", @id = "idCorrelativo", @title = "especifique correlativo de licitación", @Value = ViewBag.correlativo } })
                        @Html.ValidationMessageFor(model => model.correlativo1, "", new { @class = "text-danger" })
                    </div>

could you please tell me how to fix it?

like image 980
Pablo Tobar Avatar asked Jan 04 '23 00:01

Pablo Tobar


1 Answers

Actually, see if adding a min attribute to your editor will work. Basically want to render: min="0" in your final HTML. So in your code:

<div class="form-group">
    <div class="col-md-2">
         @Html.LabelFor(model => model.correlativo1, htmlAttributes: new { @class = "control-label" })
         @Html.EditorFor(model => model.correlativo1, new { htmlAttributes = new { @class = "form-control left-border-none", @id = "idCorrelativo", @title = "especifique correlativo de licitación", @Value = ViewBag.correlativo, @min="0" } })
         @Html.ValidationMessageFor(model => model.correlativo1, "", new { @class = "text-danger" })
    </div>
</div>

You can also use this to add the max attribute as well (if needed)

like image 194
maccettura Avatar answered Jan 18 '23 11:01

maccettura