ASP.NET Membership Provider - Validating Duplicate Email Addresses

Published on
-
1 min read

ASP.NET Membership Provider makes implementing secure authenticating membership forms more straightforward. The ASP.NET Membership Provider contains so many useful methods. But I could not find a method within the Membership class to check whether there was an existing email address in the database even though you can state in the web.config (requiresUniqueEmail) file:

<membership>
  <providers>
    <add
      name="SqlMembershipProvider"
      type="System.Web.Security.SqlMembershipProvider, ..."
      connectionStringName="LocalSqlServer"
      enablePasswordRetrieval="false"
      enablePasswordReset="true"
      requiresQuestionAndAnswer="true"
      applicationName="/"
      requiresUniqueEmail="true"
      passwordFormat="Hashed"
      maxInvalidPasswordAttempts="5"
      minRequiredPasswordLength="7"
      minRequiredNonalphanumericCharacters="1"
      passwordAttemptWindow="10"
      passwordStrengthRegularExpression=""
    />
  </providers>
</membership>

I created the following CustomValidator with a ServerValidate event to carry out the duplicate email check:

protected void DuplicateEmailCheck_ServerValidate(object source, ServerValidateEventArgs args)
    {
        //Create MembershipUserCollection to collate a list of duplicate email addresses
        MembershipUserCollection memCollection = Membership.GetUserNameByEmail(args.Value.ToString());

        //If duplicate email addresses are found then error
        if (memCollection.Count > 0)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }
    }

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.