ASP CreateUserWizard Membership provider registration user validation - c#

Im a newbie to the world of ASP and C#, I have just created my first Registration form using the CreateUserWizard Membership Provider and set up the validators which work great, Appart from the "Username". If the user name is taken the page simply refreshes and no error appears would be realy greatfull if somone could point out where I might be going wrong.
Here is my current code :
SCRIPT
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
/* User is created and setting extra parameters to profile */
TextBox UserNameTextBox = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName");
string username = UserNameTextBox.Text;
MembershipUser User = Membership.GetUser(username);
umbraco.cms.businesslogic.member.Member member = new umbraco.cms.businesslogic.member.Member((int)User.ProviderUserKey);
/* Here you can access properties for the member */
umbraco.cms.businesslogic.property.Property FullNameProperty = member.getProperty("fullname"); // Property alias
TextBox FullNameTextBox = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FullName");
FullNameProperty.Value = FullNameTextBox.Text;
Roles.AddUserToRole(CreateUserWizard1.UserName, "NuneatonMember");
}
protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)
{
Response.Redirect("/member-area.aspx");
}
CONTENT
<form runat="server">
<asp:CreateUserWizard ID="CreateUserWizard1" OnContinueButtonClick="CreateUserWizard1_ContinueButtonClick" OnCreatedUser="CreateUserWizard1_CreatedUser" runat="server">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
First Name :<asp:TextBox Runat="server" ID="FullName" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="FullNameVal" runat="server" ControlToValidate="FullName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
Last Name :<asp:TextBox Runat="server" ID="LastName" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="LastNameVal" runat="server" ControlToValidate="LastName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
Username :<asp:TextBox Runat="server" ID="UserName" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameVal" runat="server" ControlToValidate="UserName" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
E-mail :<asp:TextBox Runat="server" ID="Email" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailVal" runat="server" ControlToValidate="Email" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="Email" ValidationExpression=".*#.*\..*" ErrorMessage="* is not a valid e-mail address." ValidationGroup="CreateUserWizard1" display="dynamic"></asp:RegularExpressionValidator>
<br/>
Password :<asp:TextBox Runat="server" ID="Password" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordVal" runat="server" ControlToValidate="Password" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
Confirm Password :<asp:TextBox Runat="server" ID="ConfirmPassword" CssClass="user_info"></asp:TextBox>
<asp:RequiredFieldValidator ID="PConfirmVal" runat="server" ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
<br/>
<asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" Display="Dynamic" ValidationGroup="CreateUserWizard1" ErrorMessage="Foul: Password and Confirmation Password do not match. Fix them."></asp:CompareValidator>
<asp:literal runat="server" enableviewstate="true" id="FailureText"></asp:literal>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"></asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>

You need to add an error handler.
<asp:CreateUserWizard ID="CreateUserWizard1"
OnContinueButtonClick="CreateUserWizard1_ContinueButtonClick"
OnCreatedUser="CreateUserWizard1_CreatedUser" runat="server"
OnCreateUserError="createUserWizard_CreateUserError">
And an example of how you could implement it.
protected void createUserWizard_CreateUserError(object sender, CreateUserErrorEventArgs arguments)
{
LogCreateUserError(arguments.CreateUserError, "no user info");
}
private void LogCreateUserError(MembershipCreateStatus status, string username)
{
string reasonText = status.ToString();
switch (status)
{
case MembershipCreateStatus.DuplicateEmail:
case MembershipCreateStatus.DuplicateProviderUserKey:
case MembershipCreateStatus.DuplicateUserName:
reasonText = "The user details you entered are already registered.";
break;
case MembershipCreateStatus.InvalidAnswer:
case MembershipCreateStatus.InvalidEmail:
case MembershipCreateStatus.InvalidProviderUserKey:
case MembershipCreateStatus.InvalidQuestion:
case MembershipCreateStatus.InvalidUserName:
case MembershipCreateStatus.InvalidPassword:
reasonText = string.Format("The {0} provided was invalid.", status.ToString().Substring(7));
break;
default:
reasonText = "Due to an unknown problem, we were not able to register you at this time";
break;
}
//DO whatever with it.. ....
}

Related

How to check if the validator validated and failed validation on the page

I have multiple validators on the page that all work properly when the Submit button is clicked
However, I need to check if the validators have failed when I initiate a postback through a dropdown selected index changed event so that the failed validation messages properly persist stay
In other words I am trying to check if the certain validator has been just fired and failed
I tried the following
I checked the isValid property, but it is always true no matter what
I tried to check Page.IsValid method but it fails without the previous
Page.Validate() call
I tried to check if the failed message is visible and present but there no
such option for the validator
Thus, is there a way to check if the required validator was just fired and failed?
It seems to be something simple but I still can't find a solution
Thank you very much in advance
Came up with a solution
HTML
<asp:UpdatePanel runat="server" id="UpdatePanel1">
<ContentTemplate>
<table class="innerTable" border="0">
<tr>
<td>
<asp:DropDownList CssClass="textboxwidth" runat="server" ID="ddOrg" AutoPostBack="true" OnSelectedIndexChanged="ddOrg_SelectedIndexChanged" setCausesValidation="true"></asp:DropDownList>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator3" runat="server" Display="Dynamic" ControlToValidate="ddOrg" InitialValue="" ErrorMessage="* Required"></asp:RequiredFieldValidator>
<input type="hidden" id="hdFirmValidator" runat="server" />
<input type="hidden" id="hdPhoneValidator" runat="server" />
<input type="hidden" id="hdPhoneValidatorRegex" runat="server" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOrgOther" Enabled="false" CssClass="textboxwidth" MaxLength="100" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator12" Enabled="false" runat="server" Display="Dynamic" ControlToValidate="txtOrgOther" ErrorMessage="* Required" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox CssClass="textboxwidth" ID="txtOrgAddress" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator14" runat="server" Display="Dynamic" ControlToValidate="txtOrgAddress" ErrorMessage="* Required" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox CssClass="textboxwidth" ID="txtOrgPhone" runat="server" MaxLength="30"></asp:TextBox>
<asp:RequiredFieldValidator SetFocusOnError="true" ID="RequiredFieldValidator15" runat="server" Display="Dynamic" ControlToValidate="txtOrgPhone" ErrorMessage="* Required" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexPhone1" ValidationExpression="^.{0,30}" ErrorMessage="*Enter upto 30 digit phone number" runat="server" ControlToValidate="txtOrgPhone"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
</ContentTemplate>
JavaScript
window.onload = function () {
var btnSubmit = document.getElementById("<%=btnSubmit.ClientID%>");
function SetHiddenFields() {
var firmValidator = document.getElementById("<%=RequiredFieldValidator14.ClientID%>");
var hdFirmValidator = document.getElementById("<%=hdFirmValidator.ClientID%>");
hdFirmValidator.value = firmValidator.style.display;
var phoneValidator = document.getElementById("<%=RequiredFieldValidator15.ClientID%>");
var hdPhoneValidator = document.getElementById("<%=hdPhoneValidator.ClientID%>");
hdPhoneValidator.value = phoneValidator.style.display;
var phoneValidatorRegEx = document.getElementById("<%=regexPhone1.ClientID%>");
var hdPhoneValidatorRegex = document.getElementById("<%=hdPhoneValidatorRegex.ClientID%>");
hdPhoneValidatorRegex.value = phoneValidatorRegEx.style.display;
return true;
}
btnSubmit.onclick = SetHiddenFields; }
Codebehind
protected void ddOrg_SelectedIndexChanged(object sender, EventArgs e)
{
//Srver side code
RequiredFieldValidator3.Validate();
if (hdFirmValidator.Value != string.Empty)
{
RequiredFieldValidator14.Validate();
}
if (hdPhoneValidator.Value != string.Empty)
{
RequiredFieldValidator15.Validate();
}
if (hdPhoneValidatorRegex.Value != string.Empty)
{
regexPhone1.Validate();
}
}

Validation on a button click using RequiredFieldValidator

In the past, on button click events, I've validated without using RequiredFieldValidators. However, I thought I'd learn about them and implement them.
My old approach:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtSubject.Text.Equals("") || txtEmail.Text.Equals("") || txtComments.Text.Equals(""))
{
lblMessage.Text = "Please check all fields have been entered.";
}
//else if ...further validation statements e.g. check lengths
}
However, using RequiredFieldValidators with the same example, am I correct in saying that I don't have to check again if (txtSubject.Text.Equals("") || txtEmail.Text.Equals("") || txtComments.Text.Equals("")) like below or is it good practice to do so?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//...further validation statements e.g. check lengths
try
{
SendMail();
}
catch (Exception)
{
}
}
}
If I should still include the line, it should go at the beginning of the if (Page.IsValid), right?
HTML code:
<p>Contact Form</p>
<p>
Your name:
<asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="*"
ControlToValidate="txtName" ValidationGroup="save" /><br />
<asp:TextBox ID="txtName" runat="server" Width="250px" /><br />
Your email address:
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ErrorMessage="*"
ControlToValidate="txtEmail" ValidationGroup="save" /><br />
<asp:TextBox ID="txtEmail" runat="server" Width="250px" />
<asp:RegularExpressionValidator runat="server" ID="rfvEmail2"
SetFocusOnError="true" Text="Example: email#gmail.com" ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="Dynamic"
ValidationGroup="save" /><br />
Subject:
<asp:RequiredFieldValidator ID="rfvSubject" runat="server" ErrorMessage="*"
ControlToValidate="txtSubject" ValidationGroup="save" /><br />
<asp:TextBox ID="txtSubject" runat="server" Width="400px" /><br />
Comments:
<asp:RequiredFieldValidator ID="rfvComments" runat="server" ErrorMessage="*"
ControlToValidate="txtComments" ValidationGroup="save" /><br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="10" Width="400px" />
</p>
<p>
<asp:Button ID="btnSubmit" runat="server" Text="Send" OnClick="btnSubmit_Click" ValidationGroup="save" />
</p>
<p>
<asp:Label ID="lblMessage" runat="server" Visible="true" />
</p>
why dont you do the following?
Page.Validate("save");
if (Page.IsValid)
{
//Continue with your logic
}
else
{
//Display errors, hide controls, etc.
}
This only fires your validation group and furthermore , you can use a validation summary to display your message about the correct formats of the text boxes.
And you can display an error message then and there to display the correct format.

show availability of username on createUserWizard with available image or unavailable image

my idea is that when the user fills Username text box and goes to next textbox without refreshing page the enters username to be checks by database and if it was not empty and was available then in side of username textbox shows an available image and else shows the unavailable image.but the code that I have found is :
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">نام کاربری :</asp:Label>
</td>
<td>
<asp:TextBox ID="UserName" AutoPostBack="true" OnTextChanged="Username_Changed" size="23" class="field" runat="server"></asp:TextBox>
<br /> <div runat="server" visible="false" id="UserAvailability"></div> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="نام کاربری نمیتواند خالی باشد." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1" ForeColor="#CC0000">*</asp:RequiredFieldValidator>
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
the .cs code:
protected void Username_Changed(object sender, EventArgs e)
{
if (Membership.GetUser(UserName.Text) != null)
{
UserAvailability.InnerText = "this username is unavailable";
UserAvailability.Attributes.Add("class", "taken");
UserAvailability.Visible = true;
}
else
{
UserAvailability.InnerText = "username is available";
UserAvailability.Attributes.Add("class", "available");
UserAvailability.Visible = true;
}
}
how can I change these codes to be work by image whitout text?
Use the .innerHTML method of the DIV tag and this will allow you to use tags for your graphic instead of text message. Good luck

Validate() function doesn't fire

Here is my button.
<asp:Button ID="btnNext" runat="server" Text="Next" Style="display: none" OnClick="btnNext_Click" CausesValidation="true" ValidationGroup="vgLinR"/>
When I write ValidationGroup="vgLinR" in aspx side validation works. But I have 2 different validation group. So I need fire these 2 validation group in one button.
so I write that code at code behind :
protected void btnNext_Click(object sender, EventArgs e)
{
Page.Validate("vgLinR");
Page.Validate("vgLogR");
}
but it doesn't work. Why? How can I do that?
it will work for you ..
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 1">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 1">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 2">*</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox4" ErrorMessage="*" Font-Size="Medium" ForeColor="Red" ValidationGroup="group 2">*</asp:RequiredFieldValidator>
<br />
<br />
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="validate all" OnClick="Button1_Click"/> <br />
</div>
</form>
and write code for onclick event
protected void Button1_Click(object sender, EventArgs e)
{
Page.Validate();
}
try this
public bool Validate()
{
var isValid = false;
Page.Validate("vgLinR");
isValid = Page.IsValid;
if (isValid)
{
Page.Validate("vgLogR");
isValid = Page.IsValid;
}
return isValid;
}
Saw your answer reply for Amit a bit too late. I have updated my answer accordingly. May be you can use a similar idea if it does not fit your requirement.
In my code I am using a single ValidationSummary control without any validation group specified. Also remove the validation group from your button. Textbox a and b can be in one validation group, vg1 whereas Textbox c and d can be in another, vg2. I am not sure how you have set up your validation groups.
protected void btnNext_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Page.Validate("vg1");
ValidationSummary1.ValidationGroup = "vg1";
}
else if (RadioButton2.Checked)
{
Page.Validate("vg2");
ValidationSummary1.ValidationGroup = "vg2";
}
if (Page.IsValid)
{
//do something in here
}
}
The above code will do a server side validation. To do it on the client side as well, you would need to add a bit of javascript.
Look at another post to enable/disable Validation Group from JQuery or Javascript

ASP.net Change Password Validator

I am working on a eCommerce project which has an admin panel and shopping panels.
I have finished programming and now testing every single aspx and cs files by manually.
The problem is, I have a change password feature which is related with session and Database. The problem is I have a validators in my aspx file but they won't work. Here my codes are;
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Panel ID="Panel1" runat="server" DefaultButton="btnChange">
<div class="userForm">
<div class="formTitle">
Change Your Password
</div>
<div class="formContent">
<asp:TextBox ID="txtPassword" placeholder="Type your new password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtPassword"
ErrorMessage="RequiredFieldValidator" ForeColor="Red" Display="Dynamic" ValidationGroup="signup">Enter a password</asp:RequiredFieldValidator>
<br />
<asp:TextBox ID="txtAgainPassword" placeholder="Repeat your new password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" BorderColor="Red"
ControlToValidate="txtAgainPassword" Display="Dynamic" ErrorMessage="Enter password again."
ForeColor="Red" ValidationGroup="signup"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtPassword"
ControlToValidate="txtAgainPassword" Display="Dynamic" ErrorMessage="Password don't match."
ForeColor="Red" ValidationGroup="signup"></asp:CompareValidator>
<br />
<asp:Button ID="btnChange" runat="server" Text="Submit" OnClick="btnChange_Click" />
<br />
<asp:Label ID="lblError" Visible="False" ForeColor="Green" runat="server"></asp:Label></div>
</div>
</asp:Panel>
</asp:Content>
and the .cs part is below
protected void btnChange_Click(object sender, EventArgs e)
{
using (ZirveMarketDBEntities context = new ZirveMarketDBEntities())
{
// Atanan sessiona gore user bilgisini al - guvenlik icin onemli
int id = (int)Session["CustomerID"];
Customer cust = context.Customers.Where(i => i.CustomerID == id).FirstOrDefault();
cust.Password = txtPassword.Text;
context.SaveChanges();
}
lblError.Visible = true;
lblError.Text = "Password successfully updated";
}
The problem is, I have a 2 box for new password and type new password. Even if they are null, even if they don't match the password still changes with the value of the first part. I don't want to run server side code if they don't match or null. What am I doing wrong? Helps are pretty apreciated.
Add the 'ValidationGroup="signup"' attribute to the btnChange button.
I'd also recommend adding the below to the click event (before anything else) in case Javascript is disabled on the client:
Page.Validate("signup");
if (!Page.IsValid)
{
return;
}
You have validation groups specified on the validators, but not on the Button. Try adding the validation group to the button as well.

Categories