Solved

Checking if username exists in asp.net c#

Posted on 2012-04-12
7
858 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

828 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