Allow only integers in a textbox


I am going to show how to allow only integer in the text box. I will show here two example using Asp.net and MVC.

Asp.Net

We can use RegularExpressionValidator. From Toolbox, drag it in your aspx page and link it to textbox which needed validation.

See the sample code below:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="Only Numbers allowed" ValidationExpression="\d+"></asp:RegularExpressionValidator>

These three properties should be taken care of RegularExpressionValidator as I have used in above code.

ControlToValidate : Gets or sets the input control to validate.
ErrorMessage : Gets or sets the text for the error message displayed in a ValidationSummary control when validation fails. ValidationExpression : Gets or sets the regular expression that determines the pattern used to validate a field.

MVC

Follow these three simple steps:

1. Decorate model's properties with RegularExpression DataAnnotations.

public class SampleModel
{
    [Required]
    [RegularExpression("^[0-9]*$", ErrorMessage = "Only Numbers allowed")]
    public int OnlyInteger { get; set; }
}
      

2. Include required jquery and validation library into your page.

  @section Scripts {
     <script src="~/Scripts/jquery-1.7.1.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
  }
    

3. Use ValidationMessageFor to show error message.

@using (Html.BeginForm())
{
      @Html.TextBoxFor(x=> x.OnlyInteger)
      @Html.ValidationMessageFor(x=> x.OnlyInteger)
      <br />
      <input type="submit" value="Submit" />
}
    

Validation using Jquery

If you want plain jquery validation of html input control then we can use event key.

    <input type="text" name="onlynumber" id="onlynumber" />
    
$("#onlynumber").keypress(function (e) { //if not number display error message if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message $("#errmsg").html("only number allowed").show().fadeOut("slow"); return false; } });
See jsfiddle example here.
posted on : 6/5/2016 2:55:08 PM viewed : 3666
Latest News