Check if e-mail is valid?

Asked

Viewed 2,412 times

1

I’m using this function to check:

public static bool IsEmail(string strEmail)
{
    string strModelo = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
    if (System.Text.RegularExpressions.Regex.IsMatch(strEmail, strModelo))
    {
        return true;
    }
    else
    {
        return false;
    }
}

And the following to call the function (in the button method Salvar_Click), this is inside another if that checks if the phone has 10 digits (I put one inside the other to not have two different paths to save the record), and this is no obstacle, it will always enter this if, because telephone is mandatory field:

if (emailTextBox.Text == "") // se o campo tiver vazio
{
    this.Validate(); //ele salva
    this.clientesBindingSource.EndEdit();
    Bloq(); //Blod desativa os TextBox
    this.add.Enabled = true; // ativa o botao de Add Novo 
    mbox.msbox.sucesso("Registro salvo.", "Sucesso"); //Exibe um aviso
}
else if (IsEmail(emailTextBox.Text) == false) // se retornar que email é falso
{
    mbox.msbox.erro("Email inválido.", "Erro"); //mensagem de erro
}
else
{ //se não (caso retorne true), salva o registro
    this.Validate();
    this.clientesBindingSource.EndEdit();
    Bloq(); // bloqueia campos
    this.add.Enabled = true; //ativa botao add
    mbox.msbox.sucesso("Registro salvo.", "Sucesso"); //mensagem de sucesso
}

For me there’s nothing wrong with the code, but it doesn’t work, it accepts emails like sasadad..

1 answer

1


So I saw your code does not prevent the user to proceed, because it does not cancel the action of the user when it inserts an invalid valir. I recommend that you put the analytics in the Validating event of the field and put e.Cancel = true when the user does something wrong, like this:

else if (IsEmail(emailTextBox.Text) == false)
{
    mbox.msbox.erro("Email inválido.", "Erro"); //mensagem de erro
    e.Cancel = true; // Cancela qualquer ação do usuário. Só permitindo que ele concerte o erro.
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.