Wednesday, February 10, 2010

C# window application : How to validate mobile no.

//First : Simple Method
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == true)
{
if (textBox1.Text.Length < 10) { //do nothing } else { MessageBox.Show("Max 10 chars"); e.Handled = true; } } else { e.Handled = true; } } //Second Method using System.Text.RegularExpressions; private void btnValidatePhoneNumber_Click(object sender, EventArgs e) { Regex re = new Regex("^9[0-9]{9}"); if(re.IsMatch(txtPhone.Text.Trim()) == false || txtPhone.Text.Length>10)
{
MessageBox.Show("Invalid Indian Mobile Number !!");
txtPhone.Focus();
}
}

//With the help of JavaScript
function phone_validate(phone)
{
var phoneReg = ^((\+)?(\d{2}[-]))?(\d{10}){1}?$;
if(phoneReg.test(phone) == false)
{
alert("Phone number is not yet valid.");
}
else
{
alert("You have entered a valid phone number!");
}
}

No comments: