Solved

Checking if username exists in asp.net c#

Posted on 2012-04-12
7
811 Views
Last Modified: 2012-04-12
Hello all!

I have a standard set of controls that I am using to register a new user. I want to verify that the username chosen is indeed available in membership.

How do I do this with a custom validation control? Here's my markup:

 <asp:Label ID="lbl_username" runat="server" Text="Create a User Name:"></asp:Label>
    <asp:TextBox ID="txt_username" runat="server" class="oversize input-text"></asp:TextBox>
       <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
            ErrorMessage="Please enter a username" ControlToValidate="txt_username" 
            CssClass="form-field error"></asp:RequiredFieldValidator>
        <asp:CustomValidator ID="CustomValidator1" runat="server" 
            ControlToValidate="txt_username" ErrorMessage="CustomValidator"></asp:CustomValidator>
<br />
    <asp:Label ID="lbl_email" runat="server" Text="Email address:"></asp:Label>
    <asp:TextBox ID="txt_email" runat="server" class="oversize input-text"></asp:TextBox>  
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter your email address" ControlToValidate="txt_email"></asp:RequiredFieldValidator>
<br />    
    <asp:Label ID="lbl_password" runat="server" Text="Create a password:"></asp:Label>
    <asp:TextBox ID="txt_password" runat="server" TextMode="Password" class="oversize input-text"></asp:TextBox>  
       <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter a password" ControlToValidate="txt_password"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Minimum password length: 6" ControlToValidate="txt_password" ValidationExpression=".{6}.*" ></asp:RegularExpressionValidator>

<br />    
    <asp:Label ID="Label1" runat="server" Text="Re-enter your password:"></asp:Label>
    <asp:TextBox ID="txt_password2" runat="server" TextMode="Password" class="oversize input-text"></asp:TextBox>  
       <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Please enter your password twice" ControlToValidate="txt_password2"></asp:RequiredFieldValidator>
       <asp:CompareValidator ID="CompareValidator1" ControlToCompare="txt_password" ControlToValidate="txt_password2" runat="server" 
            ErrorMessage="Your passwords must match"></asp:CompareValidator>
                
        
        <fieldset class="nice">
        <h5>Select your plan:</h5>
        <p>Each plan includes a free trial period of 2 weeks to get started. Save more with an annual subscription!</p>
         <asp:RadioButton ID="rdo_monthly" runat="server" GroupName="Plans" Checked="True"/><asp:Label ID="lbl_rdomonth"
             runat="server" Text="$4.95 per Month"></asp:Label>
          <asp:RadioButton ID="rdo_annual" runat="server" GroupName="Plans"/><asp:Label ID="lbl_rdoannual"
             runat="server" Text="$24.95 per Year"></asp:Label>
        </fieldset>
    <asp:Button ID="btn_join" runat="server" Text="Join!" 
            class="large blue nice button radius right" onclick="btn_join_Click"/>
    

Open in new window

0
Comment
Question by:EffinGood
  • 4
  • 3
7 Comments
 
LVL 7

Expert Comment

by:Lalit Chandra
ID: 37839909
Add onservervalidate attribute to your customValidation control. like below

<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom" onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters long!" />

Now,In code behind writethe method like below

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
   //put your logic to verity the userName here like below
  Membership member= new Membership();
  bool isValidUser = member.IsValidUser(e.Value);
    if(isValidUser )
        e.IsValid = true;
    else
        e.IsValid = false;
}

Ref. Link : http://asp.net-tutorials.com/validation/custom-validator/

Hope this will help you to resolve your problem.
0
 

Author Comment

by:EffinGood
ID: 37840037
Hi Lalit!

That looks great! I implemented code as described but get an error. I am a little new at .net, so please forgive my question. What would be causing these errors, how can I resolve them?

I get Errors:

1. Cannot declare a variable of static type System.Web.Security.Membership

2. Cannot create an instance of the static class 'System.Web.Security.Membership'      

3. 'System.Web.Security.Membership' does not contain a definition for 'IsValidUser' and no extension method 'IsValidUser' accepting a first argument of type 'System.Web.Security.Membership' could be found (are you missing a using directive or an assembly reference?)      

Here's my code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;



public partial class Account_join : System.Web.UI.Page
{
    protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        //put your logic to verity the userName here like below
        Membership member = new Membership();
        bool isValidUser = member.IsValidUser(e.Value);
        if (isValidUser)
            e.IsValid = true;
        else
            e.IsValid = false;
    }


    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void btn_join_Click(object sender, EventArgs e)
    {
        var mbr_name = txt_username.Text;
        outputlabel.Text = mbr_name;
        var mbr_password = txt_password.Text;

        if (Membership.ValidateUser(mbr_name, mbr_password))
        {

            outputlabel.Text = "valid";

        }
        else
        {
            outputlabel.Text = "notvalid";
        }

    }
}

Open in new window

0
 
LVL 7

Expert Comment

by:Lalit Chandra
ID: 37840100
This error is regarding your Membership implementation.
Are you sure that you have implemented the Asp.net Membership in your application. Is the your code

Membership.ValidateUser(mbr_name, mbr_password)

is working !!!.

Is your code was working before you implement the customValidator control ???
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:EffinGood
ID: 37840119
Yes the ValidateUser is working and it was working fine before the custom validator code was added.

Anything else I can check?
0
 
LVL 7

Accepted Solution

by:
Lalit Chandra earned 500 total points
ID: 37840147
Ok. try by replacing my sugested code

   
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        //put your logic to verity the userName here like below
        Membership member = new Membership();
        bool isValidUser = member.IsValidUser(e.Value);
        if (isValidUser)
            e.IsValid = true;
        else
            e.IsValid = false;
    }

Open in new window


with

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        //put your logic to verity the userName here like below
        if (Membership.GetUser(e.Value) != null)
            e.IsValid = true;
        else
            e.IsValid = false;
    }

Open in new window


Hope this will solve your issues.
0
 

Author Comment

by:EffinGood
ID: 37840203
Thanks. That worked. Could you explain to me the difference?
0
 
LVL 7

Expert Comment

by:Lalit Chandra
ID: 37840230
My first code was just the sample, i want you to replace my code with  your Bussiness logic to determine whether the user with the name exists or not. So,As that was the sample only so it's raises the error.  But, in the next code , i m calling the Membership method to get the user information. So, it works.

Happy coding !!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now