Reputation: 634
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
and yes it shows the validation message
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?
Upvotes: 5
Views: 11589
Reputation: 58
I'm not very experienced with MVC but you could consider one of the following.
If negative values are invalid then perhaps you may want to consider using an unsigned int rather than an int.
Or..
Change the set
of your property to prevent values lower than 0.
public int correlativo1
{
get { return Correlativo1; }
set
{
if (value >= 0)
Correlativo1 = value;
else
Correlativo1 = 0;
}
}
Upvotes: 0
Reputation: 10819
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)
Upvotes: 6
Reputation: 381
@Html.EditorFor(model => model.correlativo1, new { htmlAttributes = new { @min = 0, @max = 9999, @class = "form-control left-border-none", @id = "idCorrelativo", @title = "especifique correlativo de licitación", @Value = ViewBag.correlativo } })
Upvotes: 3