C# code to validate given string in textbox is number or character

Code Snippet:

//Block 1:

 

string strValidationFailureMessage =””;

if (!IsNumeric(txtZipCode.Text.Trim()))

{

   strValidationFailureMessage = "Invalid Zip/Postal Code";

}

 

//Block 2:

 

private bool IsNumeric(string strData)

    {

        int i = 0;

        bool blnIsNumber = true;

        strData = strData.Trim();

 

        //validation for Numeric Value

        for (i = 0; i < strData.Length; i++)

        {

            blnIsNumber = char.IsDigit(strData[i]);

 

            if (blnIsNumber == false)

            {

                break;

            }

        }

 

        return blnIsNumber;

    }   

 

Note: txtZipcode is the id of my textbox.

 

You can use Block1 in the beginning of your submit button and if string ‘strValidationFailureMessage’ is not empty then don’t proceed with saving or whatever you want to do inside buttonclick event. Display the message to user.

 

Ebook Download
View all
Learn
View all