Dashamlav
Dashamlav

Reputation: 245

Always have 5 digits in TextBox

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,

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

Answers (2)

Sangram Nandkhile
Sangram Nandkhile

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

DarthTommy
DarthTommy

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

Related Questions