ASP.NET: RequiredFieldValidator with Multiple TextBoxes in ListView - asp.net

I have a ListView
<asp:ListView ....>
<asp:TextBox ID="txtComment" ... />
<asp:RequiredFieldValidator ID="rfvComment" ControlToValidate="txtComment" ... />
<act:ValidatorCalloutExtender ID="vceComment" TargetControlID="rfvComment" ... />
<asp:Button ID="btnAddComment" ... />
</asp:ListView>
lets say this ListView creates the following:
TextBox1
Button1
TextBox2
Button2
TextBox3
Button3
If I click on Button2 the RequiredFiledValidator/ValidatorCalloutExtender are applied to TextBox1 instead of TextBox2, if I click on Button3 the RequiredFiledValidator/ValidatorCalloutExtender are applied to TextBox1 as well, I want the RequiredFiledValidator/ValidatorCalloutExtender to apply to the TextBox next to the button, so if I click Button3 I want it to apply to TextBox3.
Does anyone know how can I achieve this?
thank you.

Use ValidationGroup property and generate it value dynamically:
<asp:TextBox runat="server" ID="TextBox1" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TextBox1" Text="*"
ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />
<asp:Button runat="server" Text="Click Me" ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />
Add script below at very bottom of form:
<script type="text/javascript">
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplay.call(null, val);
var isHidden = val.style.display == "none" || val.style.visibility == "hidden";
var extender = Sys.UI.Behavior.getBehaviorsByType(val, Sys.Extended.UI.ValidatorCalloutBehavior);
if (extender && extender.length == 1) {
extender = extender[0];
if (isHidden) {
extender.hide();
}
else {
extender.show(true);
}
}
}
</script>
I suppose it would be better to customize toolkit source, but I'm not in the mood to do this :) So hope this script will fix your problem

try smth like (example, that should work)
<asp:Panel ID="registration" defaultbutton="regButton" runat="server">
<asp:TextBox ID="name" Rows="1" CssClass="text" runat="server" ValidationGroup="Registration">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter your name please" Text="*" ControlToValidate="name" EnableClientScript="False" Display="Dynamic" ValidationGroup="Registration" />
<asp:TextBox ID="address" Rows="1" CssClass="text" runat="server" ValidationGroup="Registration"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter your address please" Text="*" ControlToValidate="address" EnableClientScript="False" Display="Dynamic" ValidationGroup="Registration" />
<asp:ValidationSummary DisplayMode="BulletList" EnableClientScript="false" ID="validation_sum" runat="server" HeaderText="Errors list" ValidationGroup="Registration"/>
<asp:Button runat="server" id="regButton" Text="Register please" ValidationGroup="Registration" OnClick="RegisterUser"/>
</asp:Panel>

Related

How to Use Required Field validator on a check box CHECKED true or false

I have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check
<asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />
<div class="col-xs-9 form-inline" id="PChange" style="display: none;">
<asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password" ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
<asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
<asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>
</div>
gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.
<asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />
If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?
Java script function to show/hide div.
<script type="text/javascript">
function showhidepasswordFields() {
if (document.getElementById('<%=cbPassword.ClientID%>').checked) {
document.getElementById('PChange').style.display = 'block';
}
else if (!document.getElementById('<%=cbPassword.ClientID%>').checked) {
document.getElementById('PChange').style.display = 'none';
}
}
</script>
You can use a CustomValidator for that. The first function just test wether the CheckBox is checked or not. The other one adds more logic like checking if a TextBox also has a value. Just change the ClientValidationFunction for testing.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="testCheckBoxAndTextBox"></asp:CustomValidator>
<script type="text/javascript">
function testCheckBox(sender, element) {
element.IsValid = $("#<%= CheckBox1.ClientID %>").prop('checked');
}
function testCheckBoxAndTextBox(sender, element) {
var isValid = false;
if ($("#<%= CheckBox1.ClientID %>").prop('checked') == true && $("#<%= TextBox1.ClientID %>").val() != "") {
isValid = true;
}
element.IsValid = isValid;
}
</script>
.aspx:
<asp:CheckBox ID="cbTest" runat="server" OnCheckedChanged="cbTest_CheckedChanged"></asp:CheckBox>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFV" Enabled="false" runat="server" ErrorMessage="*****" ControlToValidate="txtTest" ></asp:RequiredFieldValidator>
.aspx.cs:
protected void cbTest_CheckedChanged(object sender, EventArgs e)
{
reqFV.Enabled = cbTest.Checked;
}

asp.net "compare validator" validation

I am trying to validate fromdate & todate textboxes in asp.net using compare validator
my script is:
<table><tr><td>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text="Fromdate:"> </asp:Label>
<asp:TextBox ID="fromdatetxt" runat="server" Height="21px" Width="103px" ></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="fromdatetxt_CalendarExtender" runat="server"
Enabled="True" TargetControlID="fromdatetxt">
</ajaxToolkit:CalendarExtender>
</td>
<td>
<asp:Label ID="Label2" runat="server" Text="Todate:"></asp:Label>
<asp:TextBox ID="todatetxt" runat="server" Height="21px" Width="105px" ></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="todatetxt_CalendarExtender" runat="server"
Enabled="True" TargetControlID="todatetxt">
</ajaxToolkit:CalendarExtender>
</td>
<asp:CompareValidator ID="CompareValidatorDate" runat="server" ControlToCompare="todatetxt"
ControlToValidate="fromdatetxt" Display="None" ErrorMessage="From date cannot be greaterthan To date"
operator = "LessThanEqual" Type="Date" ValidationGroup="DateValidation"></asp:CompareValidator>
<td>
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" ValidationGroup="DateValidation" />
<asp:ValidationSummary ID="ValidationSummaryDate" ShowMessageBox="true" ShowSummary="False"
ValidationGroup="DateValidation" runat="server" /></td></tr></table>
</asp:Panel>
This is working fine! but I'm getting message box only when click the button. But I want to get message box the moment I clicked date in Todate in calendar control, and the textboxes must get clear. please help me out .
You can solve your problem using "Page_ClientValidate" function of javascript and "OnClientDateSelectionChanged" event of CalendarExtender.
You do not need to change your CompareValidator i.e.
<asp:CompareValidator ID="CompareValidatorDate" runat="server" ControlToCompare="todatetxt"
ControlToValidate="fromdatetxt" Display="None" ErrorMessage="From date cannot be greater than To date"
Operator="LessThanEqual" Type="Date" ValidationGroup="DateValidation"></asp:CompareValidator>
You need to add OnClientDateSelectionChanged event to your CalendarExtender as
<ajaxtoolkit:CalendarExtender id="todatetxt_CalendarExtender" runat="server" enabled="True"
targetcontrolid="todatetxt" OnClientDateSelectionChanged="validate" >
"validate" here is a javascript function. In that function you need to use "Page_ClientValidate" method of javascript as
var validate = function () {
var isValid = Page_ClientValidate("DateValidation"); //parameter is the validation group
if (!isValid) {
$("#<%= todatetxt.ClientID %>").val(''); //jquery to clear the textbox
}
}
You can modify the "validate" function as per your convenience.
I hope this helped.
Regards,
Samar
add Display="Dynamic" in validator
<asp:CompareValidator ID="CompareValidatorDate" runat="server" ControlToCompare="todatetxt"
ControlToValidate="fromdatetxt" Display="Dynamic" ErrorMessage="From date cannot be greaterthan To date"
Operator="LessThanEqual" Type="Date" ValidationGroup="DateValidation"></asp:CompareValidator>

ASP.NET RequiredFieldValidator : How can i bind value to " InitialValue " property?

I have the following code
<div>
<asp:DropDownList ID="testDropDownList" runat="server" ValidationGroup="testValidationGroup">
<asp:ListItem Value="Choose">[ Select Item ... ]</asp:ListItem>
<asp:ListItem Value="True">Yes</asp:ListItem>
<asp:ListItem Value="False">No</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="testRequiredFieldValidator" runat="server" ValidationGroup="testValidationGroup"
ErrorMessage="*" InitialValue="Choose" ControlToValidate="testDropDownList"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="testButton" runat="server" OnClick="testButton_Click" Text="Button"
ValidationGroup="testValidationGroup" />
<br />
</div>
in which i validate Dropdownlist by RequiredFieldValidator
If changed the value of initialvalue property to read from static property in stactic classs .. but it always give me emtpy string in runtime unless this property have the value "Choose" ...
<asp:DropDownList ID="testDropDownList" runat="server" ValidationGroup="testValidationGroup">
<asp:ListItem Value="Choose">[ Select Item ... ]</asp:ListItem>
<asp:ListItem Value="True">Yes</asp:ListItem>
<asp:ListItem Value="False">No</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="testRequiredFieldValidator" runat="server" ValidationGroup="testValidationGroup"
ErrorMessage="*" InitialValue='<%# Util.ChooseValue %>' ControlToValidate="testDropDownList">
</asp:RequiredFieldValidator>
<br />
<asp:Button ID="testButton" runat="server" OnClick="testButton_Click" Text="Button"
ValidationGroup="testValidationGroup" />
Could Any one help me to know what's the issue in my code ??
Please call
testRequiredFieldValidator.databind()
in page load event and let me know if this is still an issue.
Set InitialValue of RequiredFieldValidator on page_load event in aspx.cs page.

asp validation summary does not display even though validation fires up for requiredfieldvalidator

The Validation Summary which is to be displayed:
<asp:ValidationSummary ID="ValidationSummary1" DisplayMode="BulletList"
EnableClientScript="true" runat="server" ValidationGroup="downloadGrp" />
The required field validator:
<asp:UpdatePanel ID="UpdatePanel4" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="txtReasonForDownload"
ValidationExpression="^[\s\S]{0,500}$"
ValidationGroup="downloadGrp"
ErrorMessage="Max. 500 characters allowed!" runat="server">
</asp:RegularExpressionValidator><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtReasonForDownload" EnableClientScript="false"
ErrorMessage="Reason is required!" ValidationGroup="downloadGrp"
SetFocusOnError="true" Text="*"></asp:RequiredFieldValidator>
<asp:Label ID="Label2" runat="server" CssClass="error"
Text="Reason for Download:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine"
ValidationGroup="downloadGrp"
Width="200px" MaxLength="500" Enabled="False"></asp:TextBox><br />
</ContentTemplate>
The code behind:
protected void btnSubmitDownload_Click(object sender, EventArgs e)
{
string str1 = txtReasonForDownload.Text;
if (str1.Equals(string.Empty))
{
reqTxtReason.IsValid = false;
//Response.Write("<script> alert('Reason for Download is required!'); </script>");
} else { }
}
Although the requiredfieldvalidator is fired up, the validation summary does not display the validation.
Fixed it by enclosing validation summary in another update panel and by using the same trigger as the other update panel

How to show validation control's Error messages in Alert box?

I am using 4 required field validators,4 regular expression validators and 4 compare validators for 4 text boxes.Is it possible to show error messages
in an alert or message box when validation fails?
If possible please send code sample.
Regards,
NSJ
<form id="form1" runat="server">
<asp:Label ID="lblNameRequired" runat="server" Text="*Name :"></asp:Label>
<asp:TextBox ID="txtNameRequired" runat="server" ValidationGroup="Validation"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server" ControlToValidate="txtNameRequired"
Display="None" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblGenderRequired" runat="server" Text="*Gender :"></asp:Label>
<asp:DropDownList ID="ddlGenderRequired" runat="server" ValidationGroup="Validation">
<asp:ListItem Selected="True" Value="-1">--Select--</asp:ListItem>
<asp:ListItem Value="0">Male</asp:ListItem>
<asp:ListItem Value="1">Female</asp:ListItem>
</asp:DropDownList>
<asp:CompareValidator ID="CompareValidatorGender" runat="server" ControlToValidate="ddlGenderRequired"
Display="None" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
ValueToCompare="-1"></asp:CompareValidator>
<br />
<asp:Label ID="lblValidation" runat="server" Text="Fields marked with * are required"></asp:Label>
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate Input" ValidationGroup="Validation" />
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
ShowSummary="False" ValidationGroup="Validation" />
</form>
You should use the same ValidationGroup text on all validation controls and add a ValidationSummary with the ValidationGroup and ShowMessageBox="true"
Use the following code , just set the correct messeges that u want :
<asp:ValidationSummary ID="ValidationSummary1" ShowMessageBox ="true"
runat="server" />
<asp:textbox id="txt1" runat="server"></asp:textbox>
<asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server"
controltovalidate="txt1" errormessage="Please Enter Only Numbers" validationexpression="^[-+]?\d+(\.\d+)?$">
</asp:regularexpressionvalidator>
<asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txt1"
errormessage="please enter txt1">*</asp:requiredfieldvalidator>
<asp:textbox id="txt2" runat="server"></asp:textbox>
<asp:regularexpressionvalidator id="RegularExpressionValidator2" runat="server"
controltovalidate="txt2" errormessage="Please Enter Only Charcters" validationexpression="^[a-zA-Z\s.]*$">
</asp:regularexpressionvalidator>
<asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txt2"
errormessage="please enter txt2">*</asp:requiredfieldvalidator>
<asp:textbox id="txt3" runat="server"></asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator1" runat="server" controltovalidate="txt3"
errormessage="please enter txt3">*</asp:requiredfieldvalidator>
<asp:Button ID="btnok" runat="server" Text="ok"/>
Don't do it. Users hate alert box error messages. It is a horrible UI design. Put the error messages on the form where the user can read them and they stay while the user makes changes or moves on without having to click on an alert box. Especially when there are multiple corrections to be made, they need to be able to read the errors while they make the corrections.
You can use this function
set parameters validation message and Control ID as parameters
protected void PopupMessage(string Msg, Control controlID)
{
ScriptManager.RegisterClientScriptBlock(controlID, controlID.GetType(), "msg", "alert('" + Msg + "');", true);
}
within the button click event you can this function according to your logic
protected void btnok_Click(object sender, EventArgs e)
{
if(TextBox1.Text=="")
PopupMessage("Name is Required", btnok);
}
please follow following code which is useful for me use ShowSummary property to reduce duplication of message into your pannel
<asp:ValidationSummary ID="VS1" ShowMessageBox="true" runat="server" ShowSummary="False" />
<asp:Label ID="lblUsername" runat="server" >User name</asp:Label>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFV1" runat="server" ControlToValidate="txtUserName" ErrorMessage="Please Select Name" Display="None" SetFocusOnError="True">
</asp:RequiredFieldValidator><br />

Resources