C# createuser wizard OnDeactivate not firing - c#

I am rather confused I have got a createuser wizard control that I use with my custom user classes and role classes.
I have a step so that the admin user can create new users and assign them their roles. The OnActivate method is firing but the OnDeactivate is not. I have put break points on both methods and confirmed that it is not going into the method at all. I have included both the markup and code behind below, (sorry it is a bit long I did not want to cut anything out incase that was the problem):
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server" ContinueDestinationPageUrl="~/admin/default.aspx"
DisableCreatedUser="false" Font-Names="Verdana" BackColor="white" Font-Size="10pt"
BorderWidth="1px" BorderColor="#CCCC99" BorderStyle="Solid" CompleteSuccessText="The account has been successfully created."
UnknownErrorMessage="The account was not created. Please try again.">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep2" runat="server" Title="Step 1: Basic User Information"
OnDeactivate="UpdateCurrentLvl_OnDeactivate">
<ContentTemplate>
<table style="font-size: 10pt; font-family: Verdana" border="0" width="400">
<tr>
<td style="font-weight: bold; color: white; background-color: #6b696b" align="center"
colspan="2">
Create Your UserID
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">UserID:</asp:Label></td>
<td>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ToolTip="User Name is required."
ErrorMessage="User Name is required." ValidationGroup="CreateUserWizard1" ControlToValidate="UserName">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label></td>
<td>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ToolTip="Password is required."
ErrorMessage="Password is required." ValidationGroup="CreateUserWizard1" ControlToValidate="Password">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Re-Type Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ToolTip="Confirm Password is required."
ErrorMessage="Confirm Password is required." ValidationGroup="CreateUserWizard1"
ControlToValidate="ConfirmPassword">
*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">Email:</asp:Label>
</td>
<td>
<asp:TextBox ID="Email" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<br />
<br />
<table style="font-size: 10pt; font-family: Verdana" border="0" width="400">
<tr>
<td style="font-weight: bold; color: white; background-color: #6b696b" align="center"
colspan="2">
If You Forget Your Password
</td>
</tr>
<tr>
<td align="right">
Security Question:
</td>
<td>
<asp:DropDownList ID="Question" runat="server" Width="200">
<asp:ListItem Text="[Select a Question]" />
<asp:ListItem Text="Favorite Pet" />
<asp:ListItem Text="Mother's Maiden Name" />
<asp:ListItem Text="Who was your childhood hero?" />
<asp:ListItem Text="Your favorite pasttime?" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="QuestionRequired" runat="server" InitialValue="[Select a Question]"
ControlToValidate="Question" ErrorMessage="Select a Security Question" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" width="170">
Your Answer:
</td>
<td>
<asp:TextBox ID="Answer" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="AnswerRequired" runat="server" ControlToValidate="Answer"
ErrorMessage="RequiredFieldValidator" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br />
<br />
<table style="font-size: 10pt; font-family: Verdana" border="0" width="400">
<tr>
<td style="font-weight: bold; color: white; background-color: #6b696b" align="center"
colspan="2">
Help Us Customize Your Experience
</td>
</tr>
<tr>
<td align="right" width="170">
Set Level of the user:</td>
<td>
<asp:DropDownList ID="cLevel" runat="server">
<asp:ListItem Text="[Select a Level]" />
<asp:ListItem Text="1" />
<asp:ListItem Text="2" />
<asp:ListItem Text="3" />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" InitialValue="[Select a Level]"
ControlToValidate="cLevel" ErrorMessage="Select a Level" ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:CompareValidator ID="PasswordCompare" runat="server" ErrorMessage="The Password and Confirmation Password must match."
ValidationGroup="CreateUserWizard1" ControlToValidate="ConfirmPassword" ControlToCompare="Password"
Display="Dynamic">
</asp:CompareValidator>
</td>
</tr>
<tr>
<td style="color: red" align="center" colspan="2">
<asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
</table>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:WizardStep runat="server" ID="wsAssignUserToRoles" AllowReturn="False" Title="Step 2: Assign User To Roles"
OnActivate="AssignUserToRoles_Activate" OnDeactivate="AssignUserToRoles_Deactivate">
<table>
<tr>
<td>
Select one or more roles for the user:</td>
</tr>
<tr>
<td>
<asp:ListBox ID="AvailableRoles" runat="server" SelectionMode="Multiple" Height="104px"
Width="264px"></asp:ListBox>
</td>
</tr>
</table>
</asp:WizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep2" runat="server">
</asp:CompleteWizardStep>
</WizardSteps>
<TitleTextStyle Font-Bold="True" BackColor="#6B696B" ForeColor="White"></TitleTextStyle>
</asp:CreateUserWizard>
The code behind is:
public partial class admin_createuser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
// Create an empty Profile for the newly created user
ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);
// Populate some Profile properties off of the create user wizard
p.CurrentLevel = Int32.Parse(((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("clevel")).SelectedValue);
// Save profile - must be done since we explicitly created it
p.Save();
}
// Activate event fires when the user hits "next" in the CreateUserWizard
public void AssignUserToRoles_Activate(object sender, EventArgs e)
{
// Databind list of roles in the role manager system to a listbox in the wizard
AvailableRoles.DataSource = Roles.GetAllRoles(); ;
AvailableRoles.DataBind();
}
// Deactivate event fires when user hits "next" in the CreateUserWizard
public void AssignUserToRoles_Deactivate(object sender, EventArgs e)
{
// Add user to all selected roles from the roles listbox
for (int i = 0; i < AvailableRoles.Items.Count; i++)
{
if (AvailableRoles.Items[i].Selected == true)
Roles.AddUserToRole(CreateUserWizard1.UserName, AvailableRoles.Items[i].Value);
}
}
//set the user level to the value set in the form as it has been inserted into the DB at this point.
public void UpdateCurrentLvl_OnDeactivate(object sender, EventArgs e)
{
int level = Int32.Parse(((DropDownList)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("clevel")).SelectedValue);
MyMembershipUser myUser = (MyMembershipUser)Membership.GetUser(CreateUserWizard1.UserName);
myUser.CurrentLVL = level;
Membership.UpdateUser(myUser);
}
}

Well I seem to have found "an" answer... no idea why this would be the case.
I had the create user wizard page under /admin/createuser.aspx. When I put this in the root of the website ie.. /createuser.aspx it all worked!!!!
can't explain it but it seemed to fix the problem.. very odd!
..... edit
I spoke too soon. It seems to be a permissions thing. I think it wants to log me (the user who is creating another account) out and log in the new user, who is not in any groups yet. This means they can not access any page that has security on it in the web.config which mine do.
question is how can I stop the person being logged out and give the new user permissions?
My ultimate solution was to use this statement in the CreateUserWizard control:
LoginCreatedUser="false"
It simply stopped the user from being logged in and removed any worries of the permissions issues as the currently logged in user had to have permissions for that page in the first place.

Related

The user instance login flag is not supported on this version of SQL Server error in ChangePassword Control

I created an empty page with ChangePassword ASP.NET Control.
This page doesn't have any codebehind. But When I use this control, it shows this error.
The user instance login flag is not supported on this version of SQL
Server. The connection will be closed.
This is my ASPX Page
<asp:ChangePassword ID="ChangePassword1" runat="server"
BackColor="#F5F7F9"
style="margin-left:auto;margin-right:auto;margin-top:150px;"
BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px"
Font-Names="Arial" Font-Size="9pt" Height="281px"
onchangedpassword="ChangePassword1_ChangedPassword" Width="444px"
onchangingpassword="ChangePassword1_ChangingPassword"
oncontinuebuttonclick="ChangePassword1_ContinueButtonClick">
<CancelButtonStyle CssClass="button" Height="24px" Width="100px" />
<ChangePasswordButtonStyle CssClass="button" Height="24px" Width="150px" />
<ChangePasswordTemplate>
<table cellpadding="1" cellspacing="0" style="border-collapse:collapse;">
<tr>
<td>
<table cellpadding="0" style="height:281px;width:444px;">
<tr>
<td align="center" colspan="2"
style="color:White;background-color:#8B9ACB;font-weight:bold;">
Change Your Password</td>
</tr>
<tr>
<td colspan="2" style= "height:20px;"></td>
</tr>
<tr>
<td align="right" width="180px">
<asp:Label ID="CurrentPasswordLabel" runat="server"
AssociatedControlID="CurrentPassword">Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="CurrentPassword" runat="server" TextMode="Password"
Width="230px"></asp:TextBox>
<asp:RequiredFieldValidator ID="CurrentPasswordRequired" runat="server"
ControlToValidate="CurrentPassword" ErrorMessage="Password is required."
ToolTip="Password is required." ValidationGroup="ChangePassword1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="NewPasswordLabel" runat="server"
AssociatedControlID="NewPassword">New Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="NewPassword" runat="server" TextMode="Password" Width="230px"></asp:TextBox>
<asp:RequiredFieldValidator ID="NewPasswordRequired" runat="server"
ControlToValidate="NewPassword" ErrorMessage="New Password is required."
ToolTip="New Password is required." ValidationGroup="ChangePassword1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="ConfirmNewPasswordLabel" runat="server"
AssociatedControlID="ConfirmNewPassword">Confirm New Password:</asp:Label>
</td>
<td>
<asp:TextBox ID="ConfirmNewPassword" runat="server" TextMode="Password"
Width="230px"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmNewPasswordRequired" runat="server"
ControlToValidate="ConfirmNewPassword"
ErrorMessage="Confirm New Password is required."
ToolTip="Confirm New Password is required." ValidationGroup="ChangePassword1">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:CompareValidator ID="NewPasswordCompare" runat="server"
ControlToCompare="NewPassword" ControlToValidate="ConfirmNewPassword"
Display="Dynamic"
ErrorMessage="The Confirm New Password must match the New Password entry."
ValidationGroup="ChangePassword1"></asp:CompareValidator>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="color:Red;">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td align="right">
</td>
<td>
<asp:Button ID="ChangePasswordPushButton" runat="server"
CommandName="ChangePassword" CssClass="button" Height="24px"
Text="Change Password" ValidationGroup="ChangePassword1" Width="120px" />
<asp:Button ID="CancelPushButton" runat="server" CausesValidation="False"
CommandName="Cancel" CssClass="button" Height="24px" Text="Cancel" style="margin-left:10px;"
Width="100px" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</ChangePasswordTemplate>
<TitleTextStyle BackColor="#8B9ACB" Font-Bold="True" ForeColor="#FFFFFF" />
And, this is code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace IgnisAccess
{
public partial class UserProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ChangePassword1_ChangedPassword(object sender, EventArgs e)
{
}
protected void ChangePassword1_ChangingPassword(object sender, LoginCancelEventArgs e)
{
}
protected void ChangePassword1_ContinueButtonClick(object sender, EventArgs e)
{
}
}
}
You need to check your database connection string - it appears you're using a UserInstance=true in there somewhere.
This flag is supported only on SQL Server Express - so if you're using any other edition of SQL Server, you'll need to change that

Use viewstate for Retaining the password in asp.net

I have a form in which i am using input field with name Password1 . after postback i need to maintain the value in password using viewstate . How can i do it in ASP.NET .My code is for a registration form in which i have given a password field .i have given auto postback for the dropdown list . when the auto postback occurs the password field is getting empty. instead of that i need to maintain the value of the password as it is.
<div>
<%--<asp:ScriptManager runat="server"></asp:ScriptManager>--%>
<ajaxToolkit:ToolkitScriptManager runat="server">
</ajaxToolkit:ToolkitScriptManager>
<h1 style="color:bisque;text-align:center;">USER FORM REGISTRATION</h1>
<table class="auto-style1" style="color:crimson">
<tr>
<td class="auto-style2">First Name</td>
<td class="auto-style3">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Last Name</td>
<td class="auto-style3">
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Password</td>
<td class="auto-style3">
<input id="Password1" type="password" runat="server"/></td>
</tr>
<tr>
<td class="auto-style2">Date of Birth</td>
<td class="auto-style3">
<asp:TextBox ID="TextBox2" runat="server"
ClientIDMode="Static" ReadOnly="true"></asp:TextBox>
<asp:Image ID="imgCal" DescriptionUrl="#.jpg"
AlternateText="" runat="server" />
<ajaxToolkit:CalendarExtender ID="Calend" runat="server"
Animated="true" PopupButtonID="imgCal" TargetControlID="TextBox2">
</ajaxToolkit:CalendarExtender>
</td>
</tr>
<tr>
<td class="auto-style2">Age</td>
<td class="auto-style3">
<asp:TextBox ID="TextBox7" runat="server"
ClientIDMode="Static" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Gender</td>
<td class="auto-style3">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
RepeatDirection="Horizontal">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList></td>
</tr>
<tr>
<td class="auto-style2">Nationality</td>
<td class="auto-style3">
<asp:DropDownList ID="DropDownList1" runat="server"
Width="145px" AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="0">n1</asp:ListItem>
<asp:ListItem Value="1">loc2</asp:ListItem>
<asp:ListItem Value="2">loc3</asp:ListItem>
<asp:ListItem Value="3">other</asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox9" runat="server" Visible="false">
</asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Mobile Number</td>
<td class="auto-style3">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<asp:UpdatePanel ID="Update1" runat="server">
<ContentTemplate>
<tr>
<td class="auto-style2">Residential Adress</td>
<td class="auto-style3">
<textarea id="TextArea1" cols="20" name="TextArea1"
runat="server"></textarea></td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
</table>
</div>
by default password textbox will not retail value on postback.so you need following ways to preserve value based on this link
protected void Page_Load(object sender, EventArgs e)
{
string pwd = txtPwd.Text;
txtPwd.Attributes.Add("value", pwd);
}

JavaScript Function

I want to store TextBox value in HidenField and i am calling javascript function on button click function is calling getting message Hi but... textBox getting null....I am using asp.net TextBox and also i have tried with HTML textBox also but same scenario happing in both the case...Actually HTML code using in Ajax Tab Container may be this problem ...
How to solve such type of problem
function f11() {
alert("Hi")
alert("hi..." + document.getElementById("txthtmltextbox").value)
document.getElementById("txtuncheaderHF").value = document.getElementById("txthtmltextbox").value;
document.getElementById("txtrootFolderHF").value = document.getElementById("txthtmltextboxroot").value
}
This is my HTML code
<asp:Panel ID="pnlhfconfig" runat="server" Height="100%" Width="100%">
<table bordercolor="gainsboro" bgcolor="white" style="border-bottom-width: 1px; border-bottom-style: solid;
border-top-width: 1px; border-top-style: solid; border-left-width: 1px; border-left-style: solid;
border-right-width: 1px; border-right-style: solid; border-bottom-color: #8C8B83;
border-top-color: #8C8B83; border-left-color: #8C8B83; border-right-color: #8C8B83;"
id="TABLE2" language="javascript">
<tbody>
<tr>
<td colspan="3" bgcolor="#E5E5E5" height="20" class="topnav" style="font-size: 10px;
font-family: verdana">
<font style="color: #000000"><strong>
<asp:Literal ID="Literal4" runat='server' Text='HF Configuration'></asp:Literal>  </strong></font>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbluncheader" runat="server" Text='HotFolder UNCHeader'></asp:Label>
</td>
<td>
<input type="text" id="txthtmltextbox" name="txthtmltextbox" onblur="f1()" runat="server" MaxLength="50" Style="z-index: 102;" Width="250px" />
<asp:RequiredFieldValidator ID="rfvuncheader" runat="server"
ErrorMessage="UNCHeader is required." ControlToValidate="txthtmltextbox" Display="None"
ValidationGroup="save"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="Red" Text="*"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblrootfolder" runat="server" Text='Hot RootFolder'></asp:Label>
</td>
<td>
<input type="text" id="txthtmltextboxroot" name="txthtmltextboxroot" runat="server" MaxLength="50" Style="z-index: 102;" Width="250px" />
<%-- <asp:TextBox ID="txtrootfolder" runat="server" MaxLength="50" Width="250px"></asp:TextBox>--%><asp:RequiredFieldValidator
ID="rfvUNH" runat="server" ErrorMessage="RootFolder is required." ControlToValidate="txthtmltextboxroot"
Display="None" ValidationGroup="save"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="Label2" runat="server" Font-Bold="True" ForeColor="Red" Text="*"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<table>
<tr>
<td>
<asp:Button ID="btnsave" OnClientClick ="f1()" runat="server" Text='Save' Width="55px" BackColor="#E5E5E5"
ForeColor="Black" ValidationGroup="save" />
</td>
<td>
<asp:Button ID="btncancel" runat="server" Text='Cancel' Width="55px" BackColor="#E5E5E5"
ForeColor="Black" />
</td>
</tr>
<tr>
<td>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
ShowSummary="False" ValidationGroup="save" />
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</asp:Panel>
Hope you aware of JQuery and using JQuery, you will easily get inner control of panel. Because when your page is render on browser. Html code is something different then .NET(ASPX page).
You will get/set panel inner control value using below statement.
$("#<%=pnlhfconfig.ClientID %> input[id='<%= txtuncheaderHF.ClientID %>']").val($("#<%=pnlhfconfig.ClientID %> input[id='<%= txthtmltextbox.ClientID %>']").val());
You are using txthtmltextbox please check on console what is the actual ID of control while generating html.
Or use as
document.getElementById("<%= txthtmltextbox.ClientID%>").value

How to determine if a control has required-field validator using JQuery

I am using ASP.NET 4.5 with C#.
I have an aspx page that contains several asp textboxes. Some of them are mandatory to be filled on submitting the form while some of them and non-mandatory.
On client side OnBlur event I want to check whether the text-box is mandatory or not?
For mendatory text-boxes I already have required field validators are there in the form. Also to validate the textboxes I am using onblur="ValidatorOnChange(event);".
I have created a JQuery function which is called onblur event of each control i.e. given beolow :
$(document).ready(function () {
disableResetButton();
disableSaveButton();
$("input").blur(function (event) {
var id = event.target.id;
var value = $("#" + id).val();
if (document.getElementById(id).className.match(/(?:^|\s)txtRequireBorder-Color(?!\S)/) && value != '') {
document.getElementById(id).className = document.getElementById(id).className.replace(/(?:^|\s)txtRequireBorder-Color(?!\S)/g, ' txtBorder-Color');
}
var $validator = $("[ControlToValidate=" + this.id + "]");
alert($validator.length);
//else if (document.getElementById(id).className.match(/(?:^|\s)txtRequireBorder-Color(?!\S)/)) {
// document.getElementById(id).className = document.getElementById(id).className.replace(/(?:^|\s)txtBorder-Color(?!\S)/g, ' txtRequireBorder-Color');
});
setBorder();
});
The example of text-box on form is as below :
<tr style="vertical-align: top;">
<td align="left" class="formlabel2" valign="top" width="17%" id="tdFirstName">
<asp:Label ID="lblFName" runat="server" Text="First Name"></asp:Label>
</td>
<td align="left" valign="top" colspan="2" width="40%">
<asp:TextBox ID="txtFname" runat="server" CssClass="txtBoxWidthMiddle txtSingleline txtBack-Color txtRequireBorder-Color"
MaxLength="50" TabIndex="2" onblur="ValidatorOnChange(event);"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="rfvFname" runat="server" ControlToValidate="txtFname"
ErrorMessage="First Name is required" ValidationGroup="a" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revFname" runat="server" ControlToValidate="txtFname"
ErrorMessage="Please enter proper first name" ValidationGroup="a" Display="Dynamic"
ValidationExpression="^[\w. ,'#&$~#!"-]*$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr style="vertical-align: top;">
<td align="left" class="formlabel2" valign="top" width="20%">
<asp:Label ID="lblMName" runat="server" Text="Middle Name"></asp:Label>
</td>
<td align="left" valign="top" colspan="2">
<asp:TextBox ID="txtMname" runat="server" CssClass="txtSingleline txtBoxWidthMiddle txtBorder-Color txtBack-Color"
TabIndex="3" onKeyDown="return (event.keyCode != 13)" MaxLength="50"></asp:TextBox>
<br />
<asp:RegularExpressionValidator ID="revMname" runat="server" ControlToValidate="txtMname"
ErrorMessage="Please enter proper middle name" ValidationGroup="a" Display="Dynamic"
ValidationExpression="^[\w. ,'#&$~#!"-]*$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="left" class="formlabel2" valign="top">
<asp:Label ID="lblLName" runat="server" Text="Last Name"></asp:Label>
</td>
<td align="left" valign="top" colspan="2" width="38%">
<asp:TextBox ID="txtLname" runat="server" CssClass="txtBoxWidthMiddle txtSingleline txtBack-Color txtRequireBorder-Color"
TabIndex="4" MaxLength="50" onblur="ValidatorOnChange(event);"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="rfvLName" runat="server" ControlToValidate="txtLname"
ErrorMessage="Last Name is required" ValidationGroup="a" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revLname" runat="server" ControlToValidate="txtLname"
ErrorMessage="Please enter proper last name" ValidationGroup="a" Display="Dynamic"
ValidationExpression="^[\w. ,'#&$~#!"-]*$"></asp:RegularExpressionValidator>
</td>
</tr>
Now, How can I determine whether the blur event is called from mandatory text-box or from non-mandatory text box?
Thanks.
Because validation requires the attribute 'data-val-required' try this:
var attr = $(this).attr('data-val-required');
if(typeof attr!=='undefined' && attr!==false){
//blah blah code
}
Cheers.

RequiredFieldValidator not working if I put a code in the button's Click property ASP.NET

Q: All the RequiredFieldValidators are working when I make the btnSubmitCheckup_Click property empty. But if I put a simple code inside it, the validators are not working anymore and more, it will execute the simple code I placed inside the Click property of the button.
How will prevent the program from going forward if the required fields are blank? I've set the ControlToValidate and it works flawlessly when there is no code inside the btnSubmitCheckup_Click but if I try to put a code inside it, it will go forward and disregard the RequiredFieldValidator.
protected void btnSubmitCheckup_Click(object sender, EventArgs e)
{
Response.Write("asdasda"); ////will work even all other textboxes are empty but validators won't appear
//_con.Open();
//SqlCommand NewCheckup = new SqlCommand("dbo.NewCheckup", _con);
//NewCheckup.CommandType = CommandType.StoredProcedure;
//NewCheckup.Parameters.Add("#PatientID", SqlDbType.Int).Value = RadioButtonList_Patient.SelectedValue;
//NewCheckup.Parameters.Add("#DeptCode", SqlDbType.VarChar).Value = RadioButtonList_Department.SelectedValue;
//NewCheckup.Parameters.Add("#EmpID", SqlDbType.Int).Value = RadioButtonList_Employee.SelectedValue;
//NewCheckup.Parameters.Add("#CheckupDate", SqlDbType.Date).Value = BasicDatePicker1.SelectedDate;
//NewCheckup.Parameters.Add("#Diagnosis", SqlDbType.VarChar).Value = txtDiagnosis.Text;
//NewCheckup.ExecuteNonQuery();
//_con.Close();
//Response.Write("<script>Alert('Checkup Successfully recorded!')</script>");
}
This is my source
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NewCheckup.aspx.cs" Inherits="Clinic_WebDev.NewCheckup" %>
<%# Register assembly="BasicFrame.WebControls.BasicDatePicker" namespace="BasicFrame.WebControls" tagprefix="BDP" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bargamed Clinic - New Checkup</title>
<style type="text/css">
.style1
{
width: 100%;
}
.style2
{
width: 136px;
}
.style3
{
width: 250px;
}
#TextArea1
{
height: 104px;
width: 272px;
}
</style>
</head>
<body>
<table class="auto-style1">
<tr>
<td>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/InsertProcedure.aspx">Insert Procedure</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/InsertPatient.aspx">Insert Patient</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl="~/InsertEmployee.aspx">Insert Employee</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink4" runat="server" NavigateUrl="~/InsertDepartment.aspx">Insert Department</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink5" runat="server" NavigateUrl="~/NewCheckup.aspx">New Checkup</asp:HyperLink>
</td>
</tr>
</table>
<form id="form1" runat="server">
<table class="style1">
<tr>
<td align="right" bgcolor="#66FF66" class="style2">
Name of Patient</td>
<td bgcolor="#CCFFCC" class="style3">
<asp:TextBox ID="txtPatientName" runat="server" AutoPostBack="True"
TextMode="Search" Width="170px"></asp:TextBox>
</td>
<td bgcolor="#66FF66" style="margin-left: 80px">
Press Enter to search a patient
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="txtPatientName" ErrorMessage="Please search for a patient"
Font-Italic="True" Font-Names="Segoe UI" ForeColor="#666633"
EnableClientScript="False"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" bgcolor="#66FF66" class="style2">
Patient</td>
<td bgcolor="#CCFFCC" class="style3">
<asp:RadioButtonList ID="RadioButtonList_Patient" runat="server"
AutoPostBack="True" DataSourceID="SqlDataSource3" DataTextField="PatientName"
DataValueField="PatientID">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:CLINICConnectionString %>"
SelectCommand="SELECT PatientID, FirstName + ' ' + MiddleName + ' ' + LastName AS PatientName FROM PATIENT WHERE (FirstName + ' ' + MiddleName + ' ' + LastName LIKE '%' + #PatientName + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="txtPatientName" Name="PatientName"
PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
</td>
<td bgcolor="#66FF66">
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="RadioButtonList_Patient"
ErrorMessage="Please select the patient" Font-Italic="True" Font-Names="Segoe UI"
ForeColor="#666633"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" bgcolor="#66FF66" class="style2">
Department
</td>
<td bgcolor="#CCFFCC" class="style3">
<asp:RadioButtonList ID="RadioButtonList_Department" runat="server"
AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DeptName"
DataValueField="DeptCode"
onselectedindexchanged="RadioButtonList_Department_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CLINICConnectionString %>"
SelectCommand="SELECT DeptCode, DeptName, Status FROM DEPARTMENT">
</asp:SqlDataSource>
</td>
<td bgcolor="#66FF66">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="RadioButtonList_Department"
ErrorMessage="Please select the department" Font-Italic="True"
Font-Names="Segoe UI" ForeColor="#666633"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" bgcolor="#66FF66" class="style2">
Employee</td>
<td bgcolor="#CCFFCC" class="style3">
<asp:RadioButtonList ID="RadioButtonList_Employee" runat="server"
DataSourceID="SqlDataSource2" DataTextField="EmpName" DataValueField="EmpID">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:CLINICConnectionString %>"
SelectCommand="SELECT EmpID, EmpName, EmpStatus, Contact FROM EMPLOYEE WHERE (EmpID IN (SELECT EmpID FROM EMPLOYEE_SPECIALIZATION WHERE (DeptCode LIKE #DeptCode)))">
<SelectParameters>
<asp:ControlParameter ControlID="RadioButtonList_Department"
DefaultValue="None" Name="DeptCode" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
</td>
<td bgcolor="#66FF66">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="RadioButtonList_Employee"
ErrorMessage="Please select the employee" Font-Italic="True"
Font-Names="Segoe UI" ForeColor="#666633"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" bgcolor="#66FF66" class="style2">
<asp:Label ID="Label1" runat="server" Text="Date of Checkup"></asp:Label>
</td>
<td bgcolor="#CCFFCC" class="style3">
<BDP:BasicDatePicker ID="BasicDatePicker1" runat="server" />
</td>
<td bgcolor="#66FF66">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="BasicDatePicker1"
ErrorMessage="Please select the date of checkup" Font-Italic="True"
Font-Names="Segoe UI" ForeColor="#666633"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" bgcolor="#66FF66" class="style2">
<asp:Label ID="Label2" runat="server" Text="Diagnosis"></asp:Label>
</td>
<td bgcolor="#CCFFCC" class="style3">
<asp:TextBox ID="txtDiagnosis" runat="server" Height="67px"
TextMode="MultiLine" Width="247px"></asp:TextBox>
</td>
<td bgcolor="#66FF66">
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txtDiagnosis" ErrorMessage="Please put the diagnosis"
Font-Italic="True" Font-Names="Segoe UI" ForeColor="#666633"
ValidationGroup="ValidationGroupDaw"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td bgcolor="#66FF66" class="style2">
</td>
<td align="center" bgcolor="#CCFFCC" class="style3">
<asp:Button ID="btnSubmitCheckup" runat="server"
onclick="btnSubmitCheckup_Click" PostBackUrl="~/NewCheckup.aspx"
Text="Submit Checkup" CausesValidation="False"
ValidationGroup="ValidationGroupDaw" />
</td>
<td bgcolor="#66FF66">
</td>
</tr>
<tr>
<td bgcolor="#66FF66" class="style2">
</td>
<td bgcolor="#CCFFCC" class="style3">
</td>
<td bgcolor="#66FF66">
</td>
</tr>
</table>
</form>
</body>
</html>
are you talking your button is not working with the validation? try change your CausesValidation to true, cheer :)
<td align="center" bgcolor="#CCFFCC" class="style3">
<asp:Button ID="btnSubmitCheckup" runat="server"
onclick="btnSubmitCheckup_Click" PostBackUrl="~/NewCheckup.aspx"
Text="Submit Checkup" CausesValidation="true"
ValidationGroup="ValidationGroupDaw" />
</td>
First of all, your button contains CausesValidation="False" which will make it not call the client side validation.
The error occuring really is that it DOES validate if you don't fill in any code, but this might be because you can't tell that the button event was called regardless.
As for ensuring validation is called, you should add validation on your button click event as such:
protected void btnSubmitCheckup_Click(object sender, EventArgs e)
{
validate();
if(page.IsValid)
{
//your code here
}
else
{
//if you want to do something special if validation fails
}
}

Categories