Been using PHP for a long time but now am making a site with ASP.NET. I am attempting to have a basic user registration form but whenever I submit the form, all the data shows to be empty! Also, the tagsinput method doesnt seem to be working.
Here is a basic form, it is in a contentplaceholder. The entire body in the master page is surrounded in a <form runat="server">
<script type="text/javascript">
$(document).ready(function () {
//$("[id$=pick_user_type]").hide();
$("[id$=UserTypeList]").click(function (e) { //second step of registration
$('[id$=UserTypeList] input:checked').each(function () {
//artist
if ((this.value).toLowerCase().indexOf("artist") >= 0) {
$('#whatinstruments').show();
$('#instrumentsplayedtags').prop('disabled', false);
}
//producer
if ((this.value).toLowerCase().indexOf("producer") >= 0) {
$('#whatrecordingplatforms').show();
$('#recordingplatformstags').prop('disabled', false);
}
});
$('[id$=UserTypeList] input:not(:checked)').each(function () { //unchecked
//artist
if ((this.value).toLowerCase().indexOf("artist") >= 0) {
$('#whatinstruments').hide();
$('#instrumentsplayedtags').prop('disabled', true);
}
//producer
if ((this.value).toLowerCase().indexOf("producer") >= 0) {
$('#whatrecordingplatforms').hide();
$('#recordingplatformstags').prop('disabled', true);
}
});
});
$('#artistslikedtags').tagsInput({ //tags for listener
width: 'auto'
});
$('#instrumentsplayedtags').tagsInput({ //tags for artist
width: 'auto'
});
$('#recordingplatformstags').tagsInput({ //tags for producer
width: 'auto'
});
});
function onNextClick() {
//alert(Page_ClientValidate("UserInformation"));
//if (Page_ClientValidate("UserInformation")) {
$("[id$=registration_div]").hide('slide', { direction: 'left' }, 1000);
$("[id$=pick_user_type]").css('position', 'absolute');
$("[id$=pick_user_type]").show('slide', { direction: 'right' }, 1000);
//}
}
function onLeftClick() {
//alert(Page_ClientValidate("UserInformation"));
//if (Page_ClientValidate("UserInformation")) {
$("[id$=pick_user_type]").hide('slide', { direction: 'right' }, 1000);
$("[id$=registration_div]").show('slide', { direction: 'left' }, 1000);
//}
}
</script>
<div id="registration_div">
<table id="registration_table">
<td>
<div id="registration">
<table id="user_information_table">
<tr>
<%--first name and last name--%>
<td>
<asp:TextBox ID="FirstName" runat="server" CssClass="roundedcorner"></asp:TextBox>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkFirstName" runat="server" TargetControlID="FirstName" WatermarkText="First Name" WatermarkCssClass="watermarked roundedcorner" />
<asp:RequiredFieldValidator ID="FirstNameRequired" runat="server" ControlToValidate="FirstName" ErrorMessage="First Name is required." ToolTip="First Name is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkLastName" runat="server" TargetControlID="LastName" WatermarkText="Last Name" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="LastName" runat="server" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="LastNameRequired" runat="server" ControlToValidate="LastName" ErrorMessage="Last Name is required." ToolTip="Last Name is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<%--username--%>
<td>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkUsername" runat="server" TargetControlID="Username" WatermarkText="Username" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="UserName" runat="server" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<%--password and confirm pass--%>
<td>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkPassword" runat="server" TargetControlID="Password" WatermarkText="Password" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="Password" runat="server" TextMode="Password" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="UserInformation"><font color="red" >*</font></asp:RequiredFieldValidator>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkConfirmPassword" runat="server" TargetControlID="ConfirmPassword" WatermarkText="Confirm Password" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="ConfirmPassword" runat="server" CssClass="roundedcorner" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword" ErrorMessage="Confirm Password is required." ToolTip="Confirm Password is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
</td>
</tr>
<%--email and confirm email--%>
<tr>
<td>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkEmail" runat="server" TargetControlID="Email" WatermarkText="Email" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="Email" runat="server" Columns="48" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email" ErrorMessage="E-mail is required." ToolTip="E-mail is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="Red" ControlToValidate="Email" ValidationGroup="UserInformation" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkConfirmEmail" runat="server" TargetControlID="ConfirmEmail" WatermarkText="Confirm Email" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="ConfirmEmail" runat="server" Columns="48" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ConfirmEmail" ErrorMessage="Confirm E-mail is required." ToolTip="Confirm E-mail is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ForeColor="red" ControlToValidate="ConfirmEmail" ValidationGroup="UserInformation" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<%-- location --%>
<td>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkLocation" runat="server" TargetControlID="Location" WatermarkText="Location" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="Location" runat="server" Columns="48" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="LocationValidator" runat="server" ControlToValidate="Location" ErrorMessage="Location is required." ToolTip="Location is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<%-- birthdate --%>
<td>
<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkBirthdate" runat="server" TargetControlID="Birthdate" WatermarkText="Birthdate (mm/dd/yyyy)" WatermarkCssClass="watermarked roundedcorner" />
<asp:TextBox ID="Birthdate" runat="server" CssClass="roundedcorner"></asp:TextBox>
<asp:RequiredFieldValidator ID="BirthdayRequired" runat="server" ControlToValidate="Birthdate" ErrorMessage="Birthdate is required." ToolTip="Security question is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
<asp:CompareValidator ErrorMessage="(mm/dd/yyyy)" Display="Dynamic" ID="valcDate" ControlToValidate="Birthdate" Operator="DataTypeCheck" Type="Date" ForeColor="red" runat="server" ValidationGroup="UserInformation"></asp:CompareValidator>
<asp:RangeValidator ID="valrDate" runat="server" ControlToValidate="Birthdate" MinimumValue="12/31/1950" MaximumValue="1/1/2100" Type="Date" Text="Invalid Date" ForeColor="Red" Display="Dynamic" ValidationGroup="UserInformation" />
</td>
</tr>
<tr>
<%-- gender --%>
<td>
<%--<ajaxToolkit:TextBoxWatermarkExtender ID="WatermarkGender" runat="server" TargetControlID="Gender" WatermarkText="Birthdate (mm/dd/yyyy)" WatermarkCssClass="watermarked" />--%>
<asp:DropDownList ID="Gender" runat="server" CssClass="roundedcorner">
<asp:ListItem Value="Gender"></asp:ListItem>
<asp:ListItem Value="Male"></asp:ListItem>
<asp:ListItem Value="Female"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator InitialValue="Gender" ID="GenderRequired" runat="server" ControlToValidate="Gender" ErrorMessage="Gender is required." ToolTip="Gender is required." ValidationGroup="UserInformation"><font color="red">*</font></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="color: Red;">
<asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
</td>
</tr>
<tr>
<td>
<asp:CompareValidator ID="comparePasswords" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" ErrorMessage="Your passwords do not match!" ForeColor="red" Display="Dynamic" ValidationGroup="UserInformation" />
<asp:CompareValidator ID="EmailComparitor" runat="server" ControlToCompare="Email" ControlToValidate="ConfirmEmail" ErrorMessage="Your emails do not match!" ForeColor="Red" Display="Dynamic" ValidationGroup="UserInformation" />
<br />
<%--<asp:RegularExpressionValidator ID="PasswordRegExValidator" runat="server" ValidationExpression="^.*(?=.{8,35})(?=.*\d)(?=.*[a-zA-Z]).*$" ForeColor="Red" ControlToValidate="Password" ValidationGroup="UserInformation" ErrorMessage="Your Password must be at least 8 charaters long and contain at least 1 number."></asp:RegularExpressionValidator>--%>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
<asp:ImageButton ID="NextButton" ClientIDMode="Static" runat="server" ImageUrl="images/registration/arrowright.png"
Height="50px" onmouseover="this.src='images/registration/arrowrightgreen.png'" onmouseout="this.src='images/registration/arrowright.png'" ValidationGroup="UserInformation" OnClientClick="onNextClick()" AutoPostBack="False" OnClick="NextButton_Click"/>
</div>
<%--STEP 2--%>
<div id="pick_user_type">
<asp:ImageButton ID="LeftButton" runat="server" ImageUrl="images/registration/arrowleft.png"
Height="50px" onmouseover="this.src='images/registration/arrowleftgreen.png'"
onmouseout="this.src='images/registration/arrowleft.png'" ValidationGroup="UserSelectGroup"
OnClientClick="onLeftClick()" AutoPostBack="False"/>
<h2>Almost Done! Tell us a little more information.</h2>
<br />
<div id="pick_user_list">
<strong>Check Those That Apply to Your User Experience</strong>
<asp:CheckBoxList ID="UserTypeList" runat="server">
<asp:ListItem Selected="True" Value="Listener" Enabled="False"> Listener</asp:ListItem>
<asp:ListItem Value="Artist"> Artist</asp:ListItem>
<asp:ListItem Value="Producer"> Producer</asp:ListItem>
<asp:ListItem Value="Promoter"> Promoter</asp:ListItem>
</asp:CheckBoxList>
<br />
<strong>What music artists do you like?</strong>
<input id="artistslikedtags" type="text" class="tags" value="" runat="server" />
<br />
<div id="whatinstruments" style="display: none">
<strong>What instruments do you play?</strong>
<input id="instrumentsplayedtags" type="text" class="tags" value="" disabled="disabled" runat="server"/>
</div>
<br />
<div id="whatrecordingplatforms" style="display: none">
<strong>What recording platforms or equipment do you use?</strong>
<input id="recordingplatformstags" type="text" class="tags" value="" disabled="disabled" runat="server"/>
</div>
<br />
<strong>What mobile platform do you use?</strong><br />
<asp:DropDownList ID="MobilePlatforms" runat="server">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="iOS">iOS (Apple)</asp:ListItem>
<asp:ListItem Value="Android">Android</asp:ListItem>
<asp:ListItem Value="Windows">Windows</asp:ListItem>
<asp:ListItem Value="Blackberry">Blackberry</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator InitialValue="" ID="MobilePlatformsValidator" runat="server" ControlToValidate="MobilePlatforms" ErrorMessage="This field is required." ToolTip="This field is required." ValidationGroup="UserTypeInformation" ClientIDMode="Static"><font color="red">*</font></asp:RequiredFieldValidator>
<div style="text-align: right">
<asp:Button ID="Finish" runat="server" Text="Finish" ControlToValidate="MobilePlatforms" OnClick="FinishButton_Click" UseSubmitBehavior="False" ValidationGroup="MobilePlatforms" />
</div>
</div>
</div>
Then behind the scenes just a simple method call.
protected void FinishButton_Click(object sender, EventArgs e)
{
MembershipAdapter ma = new MembershipAdapter();
Boolean b = ma.CreateUser(UserName.Text, Email.Text, Password.Text, FirstName.Text, LastName.Text, Gender.Text, Location.Text, Birthdate.Text, MobilePlatforms.Text, "0", "0", "0", artistslikedtags.Value);
}
When I place a breakpoint on the createUser() method, all the text in the objects passed through the method are EMPTY strings!! Does anyone have an idea why this could be?
I have tried ASP.NET AutoPostBack is clearing form data
Are you doing anything during Page_Load that is setting the textbox values to blank? If that's the case you need to wrap these with
if(!Page.IsPostback)
{
//put your initialisation code for them here
}
because otherwise when you submit the form, they will be cleared every time.
Also, unkess I am going blind in my old age, there is no <form> tag in the above code?
You need to learn the various stages of the ASP.NET page lifecycle, as without understanding the basics of this, it will seem very strange of what is actually going on with ASP.NET.
Watch ASP.NET training for beginners : ASP.NET Page Life Cycle and pay specific attention to the Page_Load event, as this is where you will tend to do a lot of your work, especially dynamic content creation.
In your posted example, understanding that you can do certain things the first time the page loads versus on subsequent page requests (called postbacks), then you do the following in your page's Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Do things here that you only want to happen when the page first loads
}
else
{
// Do things here every time the page is requested, except for the first time
}
}
Related
I would like to prevent chrome browser from auto filling the username Textbox in the account login.aspx page that I have created.
I have tried setting the Textbox's AutoCompleteMode property to "None" or to "Disabled" but still nothing.
My front end code for login:
<asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false" onloggedin="LoginUser_LoggedIn">
<LayoutTemplate>
<span class="failureNotification">
<asp:Literal ID="FailureText" runat="server"></asp:Literal>
</span>
<asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification"
ValidationGroup="LoginUserValidationGroup"/>
<div class="accountInfo">
<fieldset class="login">
<legend><asp:Literal ID="Literal3" runat="server" Text="<%$ Resources:chienvh.language, AccountInformation%>" /></legend>
<p>
<%--<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>--%>
<asp:TextBox ID="UserName" runat="server" CssClass="textEntry" AutoPostBack="true" Placeholder="<%$ Resources:chienvh.language, Username%>" OnTextChanged="UserName_TextChanged"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" CssClass="failureNotification"
ErrorMessage="User Name is required." ToolTip="User Name is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p>
<%--<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>--%>
<asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password" Placeholder="<%$ Resources:chienvh.language, Password%>"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password"
CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required."
ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
</p>
<p>
<asp:DropDownList runat="server" ID="DDLSite" DataSourceID="DSSite" DataValueField="SiteID" DataTextField="Site"></asp:DropDownList>
<asp:SqlDataSource runat="server" ID="DSSite" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="Select 'Επίλέξτε Site...' [Site], 0 SiteID
union
Select [Site], [SiteID]
from Site
order by [Site]"></asp:SqlDataSource>
</p>
<p>
<asp:CheckBox ID="RememberMe" runat="server"/>
<asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
</p>
</fieldset>
<p class="submitButton">
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"/>
</p>
</div>
</LayoutTemplate>
</asp:Login>
And the back end:
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
string error = "";
string User_Name = LoginUser.UserName.ToString();
if (Common.Is_Inactive_User(User_Name, ref error) || error != "")
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
}
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();
}
}
Posted is an abridged code of my user control. I have added an update panel over radio button and want to execute a server function which will toggle between consultant drop down list and reference name text box based on the selection without a full post back. But the radio button is causing a full postback. What am I doing wrong here?
<aj:ModalPopupExtender ID="ModalPopup1" runat="server" PopupControlID="Panel1"
BackgroundCssClass="PopupBackground" CancelControlID="closeButton">
</aj:ModalPopupExtender>
<asp:Panel ID="Panel1" runat="server" CssClass="PopupPanel" align="center" style = "display:none">
<h1 class="PopupHeading">Add New Candidate</h1>
<table class="PopupTable">
<tr>
<td>
<asp:Label ID="firstNameLabel" runat="server" Text="First Name" CssClass="PopupLabel"></asp:Label>
</td>
<td>
<asp:TextBox ID="firstNameTextBox" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
<td class="ValidationError">
<asp:RequiredFieldValidator ID="nameRequiredFieldValidator" runat="server"
ValidationGroup="AddCandidateValidationGroup"
ErrorMessage="Name is required" Text="*"
ControlToValidate="firstNameTextBox" CssClass="failureNotification">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="emailLabel" runat="server" Text="Email" CssClass="PopupLabel"></asp:Label>
</td>
<td>
<asp:TextBox ID="emailTextBox" runat="server" Font-Size="14px" ></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ValidationGroup="AddCandidateValidationGroup"
ErrorMessage="Email is required" Text="*"
ControlToValidate="emailTextBox" CssClass="failureNotification">*</asp:RequiredFieldValidator>
</td>
<td>
<asp:RegularExpressionValidator ID="emailRegularExpressionValidator"
runat="server" ErrorMessage="Incorrect Email"
ValidationGroup="AddCandidateValidationGroup"
ControlToValidate="emailTextBox"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
CssClass="failureNotification" Text="Incorrect email">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="referredByLabel" runat="server" Text="Referred By" CssClass="PopupLabel"></asp:Label>
</td>
<td>
<asp:UpdatePanel ID="updatepanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:RadioButtonList ID="RefConsRadButList" runat="server" AutoPostBack="true"
RepeatDirection="Horizontal" OnSelectedIndexChanged="RefConsRadButList_SelectedIndexChanged" CausesValidation="false">
<asp:ListItem >Consultant</asp:ListItem>
<asp:ListItem>Referral</asp:ListItem>
<asp:ListItem Selected="True">N/A</asp:ListItem>
</asp:RadioButtonList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RefConsRadButList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td>
<asp:Label ID="consultantNameLabel" runat="server" Text="Consultant Name" Visible="false" CssClass="PopupLabel"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ConsultantDrDoList" runat="server" Visible="false">
<asp:ListItem>Select Consultant</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="referenceNameLabel" runat="server" Text="Reference Name" Visible = "false" CssClass="PopupLabel"></asp:Label>
</td>
<td>
<asp:TextBox ID="ReferralNameTextBox" runat="server" Visible="false"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="refNameRequiredFieldValidator" runat="server"
ValidationGroup="AddCandidateValidationGroup"
ErrorMessage="Referral name is required" Text="*"
ControlToValidate="phoneTextBox" CssClass="failureNotification">*</asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br />
<asp:Button ID="addButton" runat="server" Text="Add" onclick="addButton_Click" ValidationGroup="AddCandidateValidationGroup"/>
<asp:Button ID="closeButton" runat="server" Text="Close" />
<div id="AddStatus">
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ValidationGroup="AddCandidateValidationGroup"
HeaderText="Add user failed due to the following errors:" CssClass="PopupValidationError"/>
</div>
</asp:Panel>
instead of using updatepanel on modalpopup panel you can try something from code behind to serve the purpose.
<asp:scriptmanager id="ScriptManager1" runat="server">
</asp:scriptmanager>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" BackgroundCssClass="modalBackground"
CancelControlID="btnCancel" PopupControlID="Panel1"
TargetControlID="HiddenField1">
</asp:ModalPopupExtender>
<asp:Panel ID="Panel1" runat="server" CssClass="Panel">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="34px" RepeatDirection="Horizontal"
Width="129px" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>Option1</asp:ListItem>
<asp:ListItem>Option2</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="txt1" runat="server"
Visible="False"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server"
Visible="False"></asp:TextBox>
</asp:Panel>
===========================================
Code Behind:
===========================================
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedIndex == 0)
{
txt1.Visible = true;
ModalPopupExtender1.Show();
}
else
{
txt2.Visible = true;
ModalPopupExtender1.Show();
}
}
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.
I have a calender selector that looks like
<asp:ImageButton ID="calStartImage" runat="server" ImageUrl="../images/SmallCalendar.gif"
AlternateText="Please select start date" />
<ajaxToolkit:CalendarExtender ID="calStartDate" runat="server" TargetControlID="txtStartDate"
Format="MM/dd/yyyy" PopupButtonID="calStartImage" />
And A search button that look like this
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"
CausesValidation="false" />
When I select a date from the calender and press Search..The first time btnSearch_Click doesnt fire..If I click Search again it works fine. So I have to click the Search button twice before the click event works. This only happens if I select a date from the calender control.
Here is the full control:
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<table>
<tr>
<td class="SearchBox">
<table>
<tr>
<td colspan="2">
<b>Enter name to filter results</b>
<asp:TextBox ID="txtProjectName" runat="server"></asp:TextBox><br />
<br />
</td>
</tr>
<tr>
<td valign="middle">
<b>From:</b>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<asp:ImageButton ID="calStartImage" runat="server" ImageUrl="../images/SmallCalendar.gif"
AlternateText="Please select start date" />
<ajaxToolkit:CalendarExtender ID="calStartDate" runat="server" TargetControlID="txtStartDate"
Format="MM/dd/yyyy" PopupButtonID="calStartImage" />
<b>Thru:</b>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<asp:ImageButton runat="server" ID="calEndImage" ImageUrl="../images/SmallCalendar.gif"
AlternateText="Please select end date" />
<ajaxToolkit:CalendarExtender ID="calEndDate" runat="server" TargetControlID="txtEndDate"
Format="MM/dd/yyyy" PopupButtonID="calEndImage" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="From Date is Required"
ControlToValidate="txtStartDate" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Thru Date is Required"
ControlToValidate="txtEndDate" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Invalid From Date"
ControlToValidate="txtStartDate" Display="Dynamic" MaximumValue="1/1/2099" MinimumValue="1/1/2006"
SetFocusOnError="True" Type="Date"></asp:RangeValidator>
<asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="txtEndDate"
ErrorMessage="Invalid Thru Date" SetFocusOnError="True" Type="Date" Display="Dynamic"
MaximumValue="1/1/2999" MinimumValue="1/1/2006"></asp:RangeValidator>
<br />
</td>
</tr>
<tr>
<td align="left">
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"
CausesValidation="false" />
</td>
</tr>
</table>
</td>
<td align="right" style="width:560px">
Guide
</td>
</tr>
</table>
Here is more from the page....
<ajaxToolkit:ModalPopupExtender ID="mdlPopupExtender" runat="server" TargetControlID="btnShowPopup"
PopupControlID="pnlProject" BackgroundCssClass="modalBackground" Drag="true"
DropShadow="true" CancelControlID="btnClose" PopupDragHandleControlID="TitleBar">
</ajaxToolkit:ModalPopupExtender>
<asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
<asp:Panel ID="pnlProject" runat="server" BackColor="WhiteSmoke">
<asp:Panel ID="TitleBar" runat="server" CssClass="modalPopupTitleBar">
Add/Edit Project
</asp:Panel>
<asp:UpdatePanel ID="upPopList" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddNew" EventName="Click" />
</Triggers>
<ContentTemplate>
<table cellspacing="10">
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<b>Project Name:</b>
</td>
<td>
<asp:TextBox ID="txtProject" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqProject" runat="server" ErrorMessage="Required!"
Display="Dynamic" ControlToValidate="txtProject"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<b>Field Office:</b>
</td>
<td>
<asp:TextBox ID="txtFieldOffice" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFieldOffice" runat="server" ErrorMessage="Required!"
Display="Dynamic" ControlToValidate="txtFieldOffice"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<b>Created By:</b>
</td>
<td>
<asp:Label ID="lblCreatedBy" runat="server"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<table>
<tr>
<td>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" />
<asp:Button ID="btnClose" runat="server" Text="Close" CausesValidation="false" />
<br />
</td>
</tr>
</table>
</asp:Panel>
Any Ideas?
You need to add ValidationGroup to your validation controls so that each validation group can perform validation independently from other validation group on a specific page. more you can read here Specifying Validation Groups
Here is your code with group validation. you can change it as your environment.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td>
<table>
<tr>
<td colspan="2">
<b>Enter name to filter results</b>
<asp:TextBox ID="txtProjectName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td valign="middle">
<b>From:</b>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="formDateRequiredValidator" ValidationGroup="Date"
runat="server" ErrorMessage="Enter From Date." ControlToValidate="txtStartDate"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator1" runat="server" ValidationGroup="Date" ErrorMessage="Invalid From Date"
ControlToValidate="txtStartDate" Display="Dynamic" MaximumValue="1/1/2099" MinimumValue="1/1/2006"
SetFocusOnError="True" Type="Date"></asp:RangeValidator>
<asp:ImageButton ID="calStartImage" runat="server" AlternateText="Please select start date" />
<asp:CalendarExtender ID="calStartDate" runat="server" TargetControlID="txtStartDate"
Format="MM/dd/yyyy" PopupButtonID="calStartImage" />
<b>Thru:</b>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="endDateRequiredValidator" ValidationGroup="Date"
runat="server" ErrorMessage="Enter Thru Date." ControlToValidate="txtEndDate"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidator2" ValidationGroup="Date" runat="server" ErrorMessage="Invalid From Date"
ControlToValidate="txtStartDate" Display="Dynamic" MaximumValue="1/1/2099" MinimumValue="1/1/2006"
SetFocusOnError="True" Type="Date"></asp:RangeValidator> 
<asp:ImageButton runat="server" ID="calEndImage" ImageUrl="../images/SmallCalendar.gif"
AlternateText="Please select end date" />
<asp:CalendarExtender ID="calEndDate" runat="server" TargetControlID="txtEndDate"
Format="MM/dd/yyyy" PopupButtonID="calEndImage" />
</td>
</tr>
<tr>
<td align="left">
<asp:Button ID="btnSearch" runat="server" Text="Search" ValidationGroup="Date" CausesValidation="false" />
</td>
</tr>
</table>
</td>
<td align="right">
Guide
</td>
</tr>
</table>
<asp:ModalPopupExtender ID="mdlPopupExtender" runat="server" TargetControlID="btnShowPopup"
PopupControlID="pnlProject" BackgroundCssClass="modalBackground" Drag="true"
DropShadow="true" CancelControlID="btnClose" PopupDragHandleControlID="TitleBar">
</asp:ModalPopupExtender>
<asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
<asp:Panel ID="pnlProject" runat="server" BackColor="WhiteSmoke">
<asp:Panel ID="TitleBar" runat="server">
Add/Edit Project
<%-- I have added this Button you can replace with yours becaus specified in Triggers to run the code i need to add this(btnAddNew) Button--%>
<asp:Button ID="btnAddNew" runat="server" Text="AddNew" />
</asp:Panel>
<asp:UpdatePanel ID="upPopList" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddNew" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<b>Project Name:</b>
</td>
<td>
<asp:TextBox ID="txtProject" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqProject" ValidationGroup="ProjectInfo" runat="server"
ErrorMessage="Required!" Display="Dynamic" ControlToValidate="txtProject"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<b>Field Office:</b>
</td>
<td>
<asp:TextBox ID="txtFieldOffice" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFieldOffice" ValidationGroup="ProjectInfo" runat="server"
ErrorMessage="Required!" Display="Dynamic" ControlToValidate="txtFieldOffice"></asp:RequiredFieldValidator>
</td>
</tr>
</td> </tr>
<tr>
<td>
<b>Created By:</b>
</td>
<td>
<asp:Label ID="lblCreatedBy" runat="server"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<table>
<tr>
<td>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Save" OnClick="btnSubmit_Click" />
<asp:Button ID="btnClose" runat="server" Text="Close" CausesValidation="false" ValidationGroup="ProjectInfo"
OnClick="btnClose_Click" />
<br />
</td>
</tr>
</table>
</asp:Panel>
Hope this helps.
I don't know why but your problem can be solved by setting the CausesValidation property of btnSearch to true
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"
CausesValidation="true" />