Tuesday, August 14, 2012

How to validate US Zip Code in C#.net

       
      /// <summary>
        /// This Text event is use for USA-Zip code validation in C#.Net.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtZipcode_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtZipcode.Text))
            {
                string replaceLength = txtZipcode.Text;
                txtZipcode.Text = replaceLength.Replace("-", "");
                string findLength = txtZipcode.Text;
                int length = findLength.Length;
                if (length >= 5 && length <= 11)
                {
                    if (length == 5)
                    {
                        txtZipcode.Text = txtZipcode.Text + "-0000";
                    }
                    else
                    {
                        txtZipcode.Text = txtZipcode.Text.Substring(0, 5) + "-" +
                                            txtZipcode.Text.Substring(5, txtZipcode.Text.Length - 5);
                        string zipL = txtZipcode.Text;
                        int zipLength = zipL.Length;
                        if (zipLength == 10)
                        {
                            txtZipcode.Text = txtZipcode.Text.Substring(0, 10);
                        }
                        else
                        {
                            for (int i = 0; i < 10 - zipLength; i++)
                            {
                                txtZipcode.Text += "0";
                            }
                        } 
                    }
                     lblZip.Visible = false;
                }
                else
                {
                    lblZip.Visible = true;
                    lblZip.Text = "Invalid Zip!";
                    txtZipcode.Text = string.Empty;
                }
         }
  }

No comments: