You must Sign In to post a response.
  • Category: .NET

    validation of a textbox

    The forum thread has not been reviewed by Editors yet. Readers are advised to use their best judgement before accessing this thread.
    This thread will be reviewed shortly.
    If you think this thread contain inappropriate content, please report to webmaster.
    how to validate a textbox so that it accepts only a alphanumerics/alphabets?
  • #66
    Put this in the keypress event of the text box

    if e.KeyChar = " " then exit Sub
    If Asc(e.KeyChar) < 48 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 57 And Asc(e.KeyChar) < 65 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 95 And Asc(e.KeyChar) < 97 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 122 Then
    e.Handled = True
    End If

    The logic is to avoid all charecters except a space, integers from 48 to 57, upper case chars from 65 to 95 and lower case from 97 to 122 also remember to avoid they ascii value 8 which is backspace

  • #67
    <b> 1) Use Regular Expression Validator. </b>
    Find the sample code below

    <font size =2>
    < asp:textbox id="txtName" runat="server" MaxLength="12" tabIndex="1" >
    < /asp:textbox >

    < asp:RegularExpressionValidator id="RegularExpressionValidator2" runat="server" <br>ErrorMessage="Name should not allow Special Characters" CssClass="mandatory" <br>ControlToValidate="txtName" ValidationExpression="\w+([-+.]\w+)*" Display="Dynamic" ForeColor="" >
    < /asp:RegularExpressionValidator >
    </font>

    <b>(2) Use java script function for validate this text box.</b>
    <I>Step 1.</I>
    Create Simple javascript function. (In that function mention what are all the characters allowed in that text box). This function should be placed inside .aspx file
    <I>Step 2.<I>

    <font size =2>
    txtName.Attributes.Add("onBlur", "return ScriptFunctionName();")
    </font>

    This code should be placed inside the init or page_load event in the aspx.vb file.

  • #68
    In .Net KeyPress event is not available to track the key and validate a textbox.
    To perform validation in.Net set of validator controls are available,to validate a textbox for alphanumeric characters use <b>regularexpression validator</b>

    set the control to validate property to the textbox which is to be validated.

    set the validation expression property to <b>^[a-zA-Z0-9]+$</b>

  • #69
    Satheesh Sugumaran claims that keypress event is not available in dot net which is not correct. the keypress event is available and the first answer is the code for this event, which is posted after testing. Please don't confuse peoples. Answer if you are sure about this.

  • #70
    Hi ManojRajan,

    I 've mentioned with respect to ASP.NET(Web Application)

    You've mistaken me that i've mentioned it in VB.NET(Windows Application)

    I know that there is key press event available in VB.NET(Windows Application)

    Please note that there is no Regular Expression Validator in VB.NET(Windows Application)

    Hope this will be clear.

    PS. Those who are posting questions please be clear in your questions.

  • #71
    It's ok man. we both are right ...!!!

  • #77
    Use this regular expression :

    for checking a single character :
    /^[a-zA-Z0-9]/


    for checking a stirng :

    /^[a-zA-Z0-9]*$/

  • #83
    1.select the text box that has to be validated
    2. in the property window click event icon n u'll get the list of all available functions
    3.double click the KeyPress function.
    4. inside this function write the code for validation.

    code will look like this:

    private void textBoxUsername_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
    if (Char.IsLetterOrDigit(e.KeyChar) == true ||(e.KeyChar)==8)
    {}
    else
    {
    MessageBox.Show("Type any ");
    textBoxUsername.Text="";
    }

    }

    5. for other validations the available options are:
    The Char data type contains several Shared (static) methods that are useful for validating characters trapped by the KeyPress event. These methods include

    Char.IsDigit

    Char.IsLetter

    Char.IsLetterOrDigit

    Char.IsPunctuation

    Char.IsLower

    Char.IsUpper

    Each of these methods evaluates a character and returns a Boolean value; they are fairly self-explanatory. The Char.IsDigit function returns true if a character is a numeric digit, false if it is not. The Char.IsLower function returns true if a character is a lowercase letter, false otherwise. The other methods behave similarly. The following example uses the Char.IsNumber method to test if the key pressed is a numeric key:

  • #42386
    PUT A CHK in the txtbox1 change event

    if isNumeric(txtbox1.text) then
    e.handle=false
    end if

  • #185571
    Validation Control
    ===============

    It's a web control used to validate user form field input's in web-form.

    Types :

    . RequiredFieldValidator

    Used to enforce the field value to be mandatory.

    It won't allow to user to simply skip the form field with out giving any value if you use required field validator.
    asp:TextBox ID="txtPwd" runat="server" TextMode="Password" asp:TextBox

    asp:RequiredFieldValidator ID="RFV1" runat="server" ControlToValidate="txtPwd"
    ErrorMessage="Password Need"
    =======================================
    .CompareValidator

    It allows us to make comparison between two fields values which user has entered.

    asp:TextBox ID=" TxtPwd1" TextMode="Password" runat="server" asp:TextBox
    asp:TextBox ID=" TxtPwd2" TextMode="password" runat="server" asp:TextBox


    asp:CompareValidator ID="CV1" runat="server" ErrorMessage="Passwords not Matched" ControlToValidate="TxtPwd2"
    ControlToCompare="TxtPwd1" asp:CompareValidator

    =======================================
    .RangeValidator

    It used to check the given value of user that whether it is within the maximum and minimum range which has been set by us.

    asp:RangeValidator ID="RV1" runat="server" ErrorMessage="Value must be between 18 and 50" ControlToValidate="txtAge1"
    Type="Integer" MinimumValue="18" MaximumValue="50"
    asp:RangeValidator

    asp:TextBox ID=" txtAge1" runat="server" asp:TextBox
    =======================================

    .RegularExpressionValidator

    It used to check the given value of user that whether it is ok with our desired pattern or structure which has been set by us like expressions.

    asp:TextBox ID="txtMail" runat="server" asp:TextBox

    asp:RegularExpressionValidator ID="REV1" ControlToValidate="txtMail" runat="server"
    ErrorMessage=" Wrong e-mail entry" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" asp:RegularExpressionValidator

    =======================================
    .CustomValidator
    It's used to check user input to satisfy our desired critical requirements like a number that is divisible by 2. In this scenario we can use CustomValidator control to perform custom client side validation on user input to make sure that the number which has been entered by user is divisible by 2 or not.
    asp:CustomValidator ID="CV1" runat="server"
    ControlToValidate="txtCalculation" ClientValidationFunction="ValCalculation"
    ErrorMessage="This Number has not divisible by 2" asp:CustomValidator

    asp:TextBox ID=" txtCalculation" runat="server" asp:TextBox

    script type="text/javascript"
    function ValCalculation (oSrc,args)
    {
    args.IsValid = (args.Value % 2 == 0)
    }
    script

    =======================================
    .ValidationSummary
    ………………………………………………………………………………………………………………
    asp:TextBox ID="txtPwd" runat="server" TextMode="Password" asp:TextBox
    asp:RequiredFieldValidator ID="RFV1" runat="server" ControlToValidate="txtPwd"
    ErrorMessage="Password Need" ValidationGroup="VGrp1" * asp:RequiredFieldValidator


    asp:Button ID="btn" runat="server" Text="Login" ValidationGroup="VGrp1"

    asp:ValidationSummary ID="VS1" runat="server" ShowMessageBox="True"
    ShowSummary="False" ValidationGroup="VGrp1"

    =============

    asp:TextBox ID="txtName" runat="server" asp:TextBox

    asp:RequiredFieldValidator ID="RFV2" runat="server" ControlToValidate="txtName"
    ErrorMessage="Name required" ValidationGroup="VGrp2" asp:RequiredFieldValidator


    asp:LinkButton ID="LinkB1" runat="server" ValidationGroup="VGrp2" Login as Guest asp:LinkButton

    asp:ValidationSummary ID="VS2" runat="server" ValidationGroup="VGrp2"

    =================== =================== ====================



    ^(-)?\d+(\.\d\d)?$ 1.20
    ^\d+(\.\d\d)?$ 1.00
    ^\d+$ 0
    986
    (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$ must be between 8 and 10
    characters, contain at least
    one digit and one alphabetic
    character, and must not
    contain special characters.

    ^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d)$ 12345

    ^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-
    \.\?\,\'\/\\\+&%\$#_]*)?$ http://www.microsoft.com

    ^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$ someone@example.com


    ^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$
    (425) 555-0123
    425-555-0123
    425 555 0123
    1-425-555-0123

    ^\d{3}-\d{2}-\d{4}$ 111-11-1111

    ^[a-zA-Z''-'\s]{1,40}$ John Sjc
    J'Csjc
    ------------------------------------------------------------------------------------------------------------------------------------------------

    Change as per your need,
    Regards,
    Prakash.J.
    09964838980

  • #186307
    Just use custom validator and use this code.

    if e.KeyChar = " " then exit Sub
    If Asc(e.KeyChar) < 48 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 57 And Asc(e.KeyChar) < 65 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 95 And Asc(e.KeyChar) < 97 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 122 Then
    e.Handled = True
    End If

    This code will perfectly work but the problem with this is when u paste other characters from other program, it will allow.

    So to avoid that try to search for "Pasting" event for textbox.

  • #196364
    Use JAVA SCript Function


    function onlyNumeric()
    {
    if (event.keyCode < 48 || event.keyCode > 57)
    {
    event.returnValue = false;
    }
    }




    USE LIKE

    <input id="Txt_Store_Phone_STD" onkeypress="onlyNumeric();" onchange="return count1(Txt_Store_Phone_STD)" type="text" runat="server" style="width: 47px" maxlength="6" /> <input id="Txt_Store_Phone_NUMBER" onkeypress="onlyNumeric();" onchange="return count(Txt_Store_Phone_NUMBER)" type="text" runat="server" style="width: 99px" maxlength="10" /></td>

    RAM SINGH
    E-mail: ramsinghmscit@gmail.com
    Mobile:+91-8427242201

    Pan Card No: BIRPS8805H

  • #197122
    Put this in the keypress event of the text box

    if e.KeyChar = " " then exit Sub
    If Asc(e.KeyChar) < 48 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 57 And Asc(e.KeyChar) < 65 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 95 And Asc(e.KeyChar) < 97 Then
    e.Handled = True
    ElseIf Asc(e.KeyChar) > 122 Then
    e.Handled = True
    End If

    The logic is to avoid all charecters except a space, integers from 48 to 57, upper case chars from 65 to 95 and lower case from 97 to 122 also remember to avoid they ascii value 8 which is backspace

    RAM SINGH
    E-mail: ramsinghmscit@gmail.com
    Mobile:+91-8427242201

    Pan Card No: BIRPS8805H

  • #211872
    I 've mentioned with respect to ASP.NET(Web Application)

    You've mistaken me that i've mentioned it in VB.NET(Windows Application)

    I know that there is key press event available in VB.NET(Windows Application)

    Please note that there is no Regular Expression Validator in VB.NET(Windows Application)

    Hope this will be clear.

    RAM SINGH
    E-mail: ramsinghmscit@gmail.com
    Mobile:+91-8427242201

    Pan Card No: BIRPS8805H

  • #215548
    Public Function AcceptNumeric(ByVal str)
    If InStr("0123456789", str) > 0 Or Asc(str) = 8 Or Asc(str) = 13 Then
    AcceptNumeric = str
    Else
    AcceptNumeric = ""
    MsgBox("Enter Numeric Value...!", MsgBoxStyle.MsgBoxHelp)
    End If
    End Function
    -----------------------------------------
    Write this On text key press........
    -------------------------------------------------------
    Private Sub txtadvance_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtadvance.KeyPress
    e.KeyChar = MyMod.AcceptNumeric(e.KeyChar)
    End Sub
    -------------------------------------------------------

  • #348261
    Imports System.Data
    Imports System.Data.SqlClient
    Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Req As New RegularExpressionValidator
    Dim txtname As TextBox
    txtname = New TextBox
    txtname.ID = "txtName"
    form1.Controls.Add(txtname)

    Dim lblName As Label
    lblName = New Label
    lblName.Text = "Enter Name"
    Req.ControlToValidate = "txtName"
    Req.ErrorMessage = "Enter only Numbers"
    Req.ValidationExpression = "[0-9]*"
    Req.SetFocusOnError = True
    form1.Controls.Add(Req)
    End Sub

    End Class



    Thanks & Regards
    G.Renganathan
    Nothing is mine ,Everything is yours!!!


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.