Reputation: 1456
I'm using custom validators so I can style textboxes. However, I'm unsure how to validate an email address - possibly using a regex expression? Here's the code I'm trying to adapt:
protected void CustomValidatorBillEmail_ServerValidate(object sender, ServerValidateEventArgs args)
{
bool is_valid = txtBillingEmail.Text != "";
txtBillingEmail.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
args.IsValid = is_valid;
}
Any help, as always, would be greatly appreciated.
Upvotes: 2
Views: 8042
Reputation: 1456
Here's my solution:
protected void CustomValidatorBillEmail_ServerValidate(object sender, ServerValidateEventArgs args)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex regex = new Regex(strRegex);
bool is_valid = false;
if (regex.IsMatch(txtBillingEmail.Text))
{
is_valid = true;
}
txtBillingEmail.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
args.IsValid = is_valid;
}
Can it be improved? Need to learn!!
Upvotes: 2
Reputation: 86
.Net framework comes with a RegEx class (System.Text.RegularExpressions) which you would then supply with a regular expression to verify the email there are 100's of versions on the net.
Upvotes: 1