March

5

CreateUserWizard Set Email as Username VB.NET 3.5

Commonly, a login username is the individual’s email address. If you have used the CreateUserWizard in ASP.NET 3.5, you know that the username field and the email field are separate fields. Username is required by the wizard and email is not. If you want to populate the email field in the database with the username field, it is not obvious on the surface how to do it. Fortunately, it’s just some minor mods to the web.config and the aspx page.

web.config

In the web.config file, you will add requiresUniqueEmail=”false” to the membership provders add entry. Below is a stripped down example.

 <membership defaultProvider="MyMembership">
      <providers>
        <add name="MyMembership" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyConnectionString" requiresUniqueEmail="false" />
        </providers>
 </membership>

aspx page

On the aspx page itself, you will add RequireEmail=”false” so the email textbox is not mandatory and a call to a function in the OnCreatedUser event to the CreateUserWizard. Also, some validation is added to the username field to ensure that it is in a valid email format.

<asp:CreateUserWizard ID="CreateUserWizard1" OnCreatedUser="CreateUserWizard1_CreatedUser" RequireEmail="false" Runat="server">

<asp:TextBox ID="UserName" Width="200" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="E-mail is required."ValidationGroup="CreateUserWizard1" />

<asp:RegularExpressionValidator ID="regEmail" ControlToValidate="UserName" Text="Invalid e-mail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Runat="server" />

The function fires right after the user is created and updates the email field with the username.

Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As EventArgs)
        Dim userNameTextBox As TextBox = CType(CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserName"), TextBox)
        Dim user As MembershipUser = Membership.GetUser(userNameTextBox.Text)

        user.Email = user.UserName
        Membership.UpdateUser(user)
    End Sub

No related posts.

1 Comment for CreateUserWizard Set Email as Username VB.NET 3.5


Gary
April 3, 2010

Thanks just what I was looking for.
Gary

Leave a comment

Why ask?

 

« | »