ASP.NET Custom Validate Email

1.3k views Asked by At

For my school exam we have to validate a email-address, but are not allowed to use the RegularExpressionValidator. I am trying to solve this with the Custom Validator but i can't figure it out. (Email input is in text box (tb_email).

I am trying to solve it like this:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (tb_email.Text ==  \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* )
        {
            args.IsValid = true;
        } 
        else
        {
            args.IsValid = false;
        }
    }

or something like this comes to mind:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (tb_email.Text != "")
        {
            string filter = \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*; 
            args.IsValid = true;
        } 
        else
        {
            args.IsValid = false;
        }
    }

I am getting massive errors and I just can't figure out how this can be done. I have done a lot of searching but I only find answers like : just use regular expression validators or code solutions in Java (which I haven't learned yet). I would really appreciate an good answer! Thanks

1

There are 1 answers

0
Elisheva Wasserman On

Can you use regular expression without REgularExpressionValidator? if so then:

using System;
using System.Text.RegularExpressions;

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (tb_email.Text != "")
    {
        string filter = \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*; 

       Regex regex = new Regex(filter );
   Match match = regex.Match(tb_email.Text );
    if (match.Success)
    {
         args.IsValid=true; }
        else
        {
         args.IsValid = false;  

  } 
}

On client side (javascript) see this post:

Validating email addresses using jQuery and regex