Reputation: 245
I need a TextBox
in ASP.NET MVC
such that it can only take 5 digits, not more, not less and if the number entered starts with 0
, then the value displayed in the TextBox
is starting with a '0`.
Example,
If I enter 12345
, the TextBox
should display 12345
. Even if I try to enter another digit beyond the last 5
, it should not allow me to do so. Similarly, if I enter less than 5
digits, I should be prompted to enter a total of 5
digits.
If I enter 01234
, the TextBox
should display 01234
and not 1234
.
As I need to store in the database, exactly how it is in the TextBox
, I have declared the field as string
.
Upvotes: 1
Views: 3029
Reputation: 18192
You can use min
and max
html attributes but they are not enforced in all the browsers so it's better to rely on Javascript/jQuery.
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
var $this = $(this);
var val = $this.val();
var valLength = val.length;
var maxCount = $this.attr('max');
if(valLength>maxCount){
$this.val($this.val().substring(0,maxCount));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="test-input" type="number" max="5" />
Also, it would not be a good experience to check minimum characters validation while user is entering the value (keyup/change event), so better to check that on form submit.
Upvotes: 3
Reputation: 457
I'm assuming that you are using an @Html.Text box in razor syntax. If so then this should work for you:
@Html.TextBox("FiveDigits", "", new { placeholder = "Enter 5 digits"})
Would go in your view, and this would go in your controller:
if (TheForm["FiveDigits"] > 99999 || TheForm["FiveDigits"] < 10000 || String.IsNullorEmpty(tablename.TextHasMoreThanFiveDigits))
{
ModelState.AddModelError("TextHasMoreThanFiveDigits", "You must enter a 5 digit number");
return View(ViewWithTextBox);
} else { do database stuff}
I don't know the names of your variables so I made some up, but I have very similar logic in a program I work on
Upvotes: 0