Check if email is valid?

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 Salvar_Click button method), this is inside another if that checks if the phone has 10 digits (put one inside the other so that it does not have two distinct paths to save the record), and this is not a hindrance, it will always enter this if , because phone is a required 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 is nothing wrong with the code, but it does not work, it accepts emails like sasadad ..

    
asked by anonymous 05.07.2015 / 02:09

1 answer

1

From what I saw your code does not prevent the user from proceeding, as it does not cancel the action of the user when it inserts an invalid value. I recommend that you post the analyzes 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.
}
    
05.07.2015 / 05:46