Tuesday, February 7, 2012

Only Number validation in Textbox Asp.net, Jquery, JavaScript


Pure Asp.net
Pure asp.net we have using Regular Expression Validator
The Regular Expression is ^\d+$

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtNo" ValidationGroup="OnlyNumber" runat="server"></asp:TextBox>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNo"
            ErrorMessage="Please Enter Only Numbers" ValidationExpression="^\d+$" ValidationGroup="check"></asp:RegularExpressionValidator>
        <asp:Button ID="Button1" runat="server" ValidationGroup="check" Text="Submit "></asp:Button>
    </div>
    </form>

Jquery with asp.net
Only numbers can enter into that Textbox.
The next way is Jquery with asp.net flow the steps
Add the Jquery Reference





<script src=" http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
  $(document).ready(function () {
            $('input[numeric]').keyup(function () {
                var d = $(this).attr('numeric');
                var val = $(this).val();
                var orignalValue = val;
                val = val.replace(/[0-9]*/g, "");
                var msg = "Only Integer Values allowed.";
                if (val != '') {
                    orignalValue = orignalValue.replace(/([^0-9].*)/g, "")
                    $(this).val(orignalValue);
                    alert(msg);
                }
            });
        });

    </script>

    <asp:TextBox ID="txtCardno" numeric="integer"                                                runat="server"></asp:TextBox>


Javascript with asp.net
<script type="text/javascript">
    function numberOnlyExample() {
        if ((event.keyCode < 48) || (event.keyCode > 57))
            return false;
    }
</script>


Call this function in onKeyPress event of textbox.
Write this code in html source of textbox
.
<asp:TextBox ID="TextBox1" onKeyPress="return validateNumbersOnly();"runat="server"></asp:TextBox>

7 comments:

  1. Replies
    1. the three type solution here your link only one solution is there

      Delete


  2. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training institute in velachery

    ReplyDelete