Solved

Checking if username exists in asp.net c#

Posted on 2012-04-12
7
845 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

831 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