3

In My model I use

[Display(Name ="No Of Children")]       
public Nullable<int> NoOFChildren { get; set; } 

And in my view I use

<div class="col-lg-6">
    @Html.EditorFor(model => model.NoOFChildren, new { htmlAttributes = new { @class = "form-control", placeholder = "No Of Children" } })
</div>

When I run the page it will show textbox like following image

enter image description here

I want to restrict this textbox to accept number less than zero. When number is zero the down arrow should be disable. How I can do that?

jQuery validation may be one option but I don’t want to use that until and unless no alternative is valuable. Is there any DataAnotation validation attributes is there that can do it or any HTML5 elements that may do it automatically without writing additional scripts?

Namit Kumar
  • 111
  • 1
  • 5
  • 11
  • 4
    You can add a `[Range]` attribute to display a client side error message. In order to hide show the spinner buttons, you need jquery to modify the css dynamically as explained in [these answers](http://stackoverflow.com/questions/3790935/can-i-hide-the-html5-number-input-s-spin-box) –  Feb 27 '15 at 06:50
  • [Range] can display error message but i don't want to display error message. Is there any HTML5 element available that can do this for me ? – Namit Kumar Feb 27 '15 at 06:56
  • 1
    You can add the `min="0"` attibute - it wont hide the arrow, just prevent it decrementing the value when clicked (but I believe this is not well supported across browsers). If you want to hide the button then refer the link in my first comment. In any case HTML5 is not supported in older browsers so you should still have the `[Range]` attribute anyway –  Feb 27 '15 at 07:01

1 Answers1

2

You can either do this using jquery or you can add a data anotation on your model

[Display(Name ="No Of Children")]       
[Range(0, 15, ErrorMessage = " ")]
public Nullable<int> NoOFChildren { get; set; } 

This should restrict the user.
Also leaving the ErrorMessageblank (it has a space inside, not technically blank) will not display error message on the view

Update You can try this:

 @Html.EditorFor(model => model.NoOFChildren, new { htmlAttributes = new { @class = "form-control", placeholder = "No Of Children",min="0" ,max="100",step="5" } })

this will set min as 0 max as 100 and increment on every click by 5.

Nikitesh
  • 1,287
  • 1
  • 17
  • 38