NiksJ
NiksJ

Reputation: 421

cshtml TextBoxFor should only accept numbers(0-10)

I have a textbox, in a table. i.e,

I have to only allow numbers in textbox, and I am trying to do as below.

But, (+ and - and .) symbols are being accepted in the textbox( Ex: "+123", "-123", ".123") though I am doing @type="number"

Any help would be appreciated.

My code

<td>@Html.TextBoxFor(modelItem => item.Amount, new { @id = "amount", @type = "number"})</td>

Upvotes: 0

Views: 1671

Answers (1)

teo van kot
teo van kot

Reputation: 12491

You can use unobtrusivevalidation for this case.

After you add scripts and change Web.Config you should just annotate your model property:

public class YourViewModel
{
   [Range(typeof(int), "0", "10", ErrorMessage = "{0} can only be between {1} and {2}")]
   public int Amount { get; set; }
   /* other properties */
}

And then if you write just like this:

<td>@Html.TextBoxFor(x => x.Amount)</td>

Razor will create input with client validation.

Upvotes: 1

Related Questions