In a multigrid I am validating two controls like date and amount. It is validating correctly when I press the tabevent. When I press the save button it is not validating. I am using two validations groups and two validation summary. Then in save button Ialso tried onclientclick() function with javascript it is working fine but if I give the correct value in date and amount records, it is not saving. how to over come this.
Date
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox ID="txtDate" Text='<%# Bind("AD_REF_DATE") %>' runat="server" CausesValidation="true"
ValidationGroup="group" Width="80px" AutoPostBack="true" OnTextChanged="txtDate_TextChanged"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CompareValidator ID="dateValidater" runat="server" ControlToValidate="txtDate"
Operator="DataTypeCheck" Type="Date" ValidationGroup="group" EnableClientScript="true"
ErrorMessage="Please enter a valid date (mm/dd/yyyy)." SetFocusOnError="true" Display="None">*</asp:CompareValidator>
</ItemTemplate>
</asp:TemplateField>
Amount
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="txtAmount" MaxLength="17" Text='<%# Bind("AD_AMOUNT") %>' CausesValidation="true"
ValidationGroup="req" runat="server" AutoPostBack="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RegularExpressionValidator ID="regVal1" runat="server" ControlToValidate="txtAmount"
ErrorMessage="Format(13int,5deci)" ValidationExpression="^[1-9]\d{0,12}(\.\d{1,2})?%?$"
ValidationGroup="req" Display="None" EnableClientScript="true" SetFocusOnError="true">
</asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
validations summary:
<asp:ValidationSummary ID="ValidationSummary3" runat="server" ValidationGroup="req"
HeaderText="Amount:Invalid Format" DisplayMode="BulletList" ShowMessageBox="true"
ShowSummary="false" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="group"
HeaderText="Date:Invalid Format" DisplayMode="BulletList" ShowMessageBox="true"
ShowSummary="false" />
button save:
<asp:Button ID="ButtonSave" runat="server" CssClass="button" CausesValidation="true" Text="<%$Resources:TJFAS501, ButtonSave %>"
OnClick="ButtonSave_Click" TabIndex="6" />
How to validate this in the button save also two popup box should be shown?
You might want to try firing the validate function for both groups manually via the button's OnClientClick since you have two validation groups you need to validate against. Currently your validation is not firing because you do not have any ValidationGroup assigned to your button so it is just looking for validators with no ValidationGroup defined (yours groups are: group and req).
You can call Page_ClientValidate() via javascript to fire off the validation checks manually (be sure to set CauseValidation on your button to false) and it has an optional parameter that takes the validation group.
<asp:Button ID="yourButton" runat="server" OnClick="ButtonSave_Click"
CausesValidation="false" TabIndex="6"
OnClientClick="return (Page_ClientValidate('group') && Page_ClientValidate('req'));" />
You can read more about Page_ClientValidate on MSDN.
It would be easier to just have one validation group for each action (eg. your button) but I assume you need two groups for some reason.
Try this..
<script type="text/javascript">
function Validate() {
var isValid = false;
isValid = Page_ClientValidate('Group1');
if (isValid) {
isValid = Page_ClientValidate('Group2');
}
return isValid;
}
</script>
Related
I have reapeater in my code and trying to validate the textbox using asp.net required field validator. But validation messsage
not displaying, i opened the developer tools and found that style="visibility:hidden" added into the required field validator.
Below is my code
<asp:Repeater ID="RepeaterCategory" runat="server" DataSource='<%# this.Categories.Count==0 ? null : this.Categories %>'>
<ItemTemplate>
<div>
<asp:Label runat="server" Visible="true" Text="Category" />
<asp:PlaceHolder runat="server" Visible="true">
<asp:TextBox ID="txtCategoryID" runat="server" value="1" />
<asp:TextBox ID="txtCategoryName" runat="server" value="<%# (Container.DataItem as Category).Name %>" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="<br/>This is a required field" ControlToValidate="txtCategoryName" ValidationGroup="NewCategoryGroup"></asp:RequiredFieldValidator>
</asp:PlaceHolder>
<asp:LinkButton runat="server" ToolTip="Save" ValidationGroup="NewCategoryGroup" OnClick="SaveCategory_Click"><img src='<%# some path%>/images/save.gif' /></asp:LinkButton>
<asp:LinkButton runat="server" ToolTip="Close" OnClick="CloseCategory_Click"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
Code behind file
protected void SaveCategory_Click(object o, EventArgs e)
{
Page.Validate("NewCategoryGroup");
if (!Page.IsValid)
return;
//logic
}
Can anyone suggest how to enable it?
The style="visibility:hidden" is default behavior. It changes to style="visibility: visible;" when the error message needs displaying. Therefore you probably don't have an error.
The validator is a 'RequiredFieldValidator', and since the textbox that is being validated is already filled with the value "TestCategory" there are no errors. If you just add text to the Save button (which has no ID tag) so that it becomes visible, remove the value from the txtCategoryName textbox and click the save button you will see the error message.
This works:
<asp:TextBox ID="txtCategoryName" runat="server" value="" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="<br/>This is a required field" ControlToValidate="txtCategoryName" ValidationGroup="NewCategoryGroup"></asp:RequiredFieldValidator>
<asp:LinkButton runat="server" ToolTip="Save" ValidationGroup="NewCategoryGroup" OnClick="SaveCategory_Click" ID="LinkButton1">Save Me!</asp:LinkButton>
You don't need this code
Page.Validate("NewCategoryGroup");
if (!Page.IsValid)
Another advantage is that the validators work now without a postback, this saves a roundtrip to the server.
And ALWAYS do server side validation also, but try to do the first validation without postback.
UPDATE
What you want is probably validation per item. And since your validationgroup is always the same it will fire for all textboxes. Try this:
<asp:Repeater ID="RepeaterCategory" runat="server">
<ItemTemplate>
<div>
<asp:TextBox ID="txtCategoryName" runat="server" ValidationGroup='<%# "myVal_" + Container.ItemIndex %>' Text='<%# Eval("Category") %>' />
<br />
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ErrorMessage="This is a required field<br />" ControlToValidate="txtCategoryName" ValidationGroup='<%# "myVal_" + Container.ItemIndex %>'></asp:RequiredFieldValidator>
<asp:LinkButton runat="server" ValidationGroup='<%# "myVal_" + Container.ItemIndex %>' OnClick="Button1_Click" ID="LinkButton1">Save Me!</asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
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>
After validation failed, I have a problem with controls (dropdownlist or button) that should cause a new postback. I will try to explain it clearly...
The purpose of my page is to save fives dates in a database. The page has the following controls:
Five textboxes, each one containing a date
A reset button (CausesValidation=false) to restore a default date in one of the 5 textboxes
A dropdown list (AutoPostback=true, CausesValidation=false) of predefined templates that applies 5 dates to the 5 textboxes
A button to save the dates to the database
The textboxes can be edited manually. So, when I click the Save button, if the format of the dates is not valid, the validation fails and the save is aborted. The problem is just after that. If I click on the Reset button or select an item in the dropdownlist, the postback is not triggered. If I try again, then it works. Is there a way to make it work the first time after the first validation failed? I tried deactivating the validation on the client-side when changing the selection in the dropdownlist but the postback still does not occur.
Here is the relevant part of the code:
<asp:DropDownList ID="cboScheduleTemplates" runat="server" AutoPostBack="true" CausesValidation="false" />
<asp:TextBox ID="txtDateDelivery1" runat="server" />
<asp:RegularExpressionValidator ID="revDateDelivery1" runat="server" Display="Dynamic" ValidationGroup="Schedule" ControlToValidate="txtDateDelivery1" Text="*" />
<asp:TextBox ID="txtDateYearbookQuantity" runat="server" />
<asp:RegularExpressionValidator ID="revDateYearbookQuantity" runat="server" Display="Dynamic" ValidationGroup="Schedule" ControlToValidate="txtDateYearbookQuantity" Text="*" />
<asp:TextBox ID="txtDateDelivery2" runat="server" />
<asp:RegularExpressionValidator ID="revDateDelivery2" runat="server" Display="Dynamic" ValidationGroup="Schedule" ControlToValidate="txtDateDelivery2" Text="*" />
<asp:TextBox ID="txtDatePersonalizations" runat="server" />
<asp:RegularExpressionValidator ID="revDatePersonalizations" runat="server" Display="Dynamic" ValidationGroup="Schedule" ControlToValidate="txtDatePersonalizations" Text="*" />
<asp:TextBox ID="txtDateDelivery3" runat="server" />
<asp:Button ID="btnSetDefaultDelivery3" runat="server" ValidationGroup="Schedule" CausesValidation="false" />
<asp:RegularExpressionValidator ID="revDateDelivery3" runat="server" Display="Dynamic" ValidationGroup="Schedule" ControlToValidate="txtDateDelivery3" Text="*" />
<asp:Button ID="btnSaveSchedule" runat="server" CssClass="btnAction" Text="Save" ValidationGroup="Schedule" />
<asp:ValidationSummary ID="validationSummarySchedule" runat="server" ValidationGroup="Schedule" DisplayMode="List" />
As suggested in this post, the problem comes from calls to Page_ClientValidate. So I wrapped the client function like this and the problem went away:
function DoPageClientValidate(validationGroupName)
{
var result = Page_ClientValidate(validationGroupName);
Page_BlockSubmit = false;
return result;
}
Trying to access a RequiredFieldValidator control that's inside a GridView in the RowCommand event and having trouble.
Here's the partial GridView code:
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:TextBox ID="txtPassword" runat="server" CssClass="GridViewTextbox" TextMode="Password" Text='<%#Eval("WebPassword") %>' Enabled="false"></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWebPassword" runat="server" TextMode="Password" Text='<%#Eval("WebPassword") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server" SetFocusOnError="true"
ControlToValidate="txtWebPassword" Display="None" ErrorMessage='<%# Constants.Strings.PasswordRequired %>'></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddWebPassword" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAddPassword" runat="server" SetFocusOnError="true"
ControlToValidate="txtAddWebPassword" Display="None" ErrorMessage='<%# Constants.Strings.PasswordRequired %>'></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
As you can see, there's a RFV for the EditTemplate and FooterTemplate. My issue is this; when the page loads, it has all the records in it, including an emtpy row at the bottom (Footer). If I click Edit on a populated row, the data is populated correctly, then when I hit UPDATE, I get all the error messages from the FOOTER RFV's firing off, which isn't correct. So, in the RowCommand event, I'd like to attempt this: If the user clicks the EDIT button, then disable all the RFV's in the footer row (the add new row), if they click anything else, enable them.
Ideas?
Sorry, meant to put this in the first time. In the RowCommand event, I am able to find the control but when I set the properties to something bogus, it seems to get overridden later, by the RowDataBound event:
RequiredFieldValidator rfv = (RequiredFieldValidator)gvUsers.FooterRow.FindControl("rfvAddWebLogin");
rfv.ControlToValidate = string.Empty;
rfv.ErrorMessage = "sdfgsdfgsdgsdfgsdfgsdfgsdfg";
rfv.Enabled = false;
You should use different ValidationGroups in your EditItemTemplate and FooterItemplate:
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="BtnEdit" CausesValidation="False" Text="Edit" CommandName="Edit" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" ValidationGroup="UpdateUser" Text="Update" CommandName="Update" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="BtnInsert" ValidationGroup="InsertUser" Text="Add" CommandName="Insert" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:TextBox ID="txtPassword" runat="server" CssClass="GridViewTextbox" TextMode="Password"
Text='<%#Eval("WebPassword") %>' Enabled="false"></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWebPassword" ValidationGroup="UpdateUser" runat="server" TextMode="Password" Text='<%#Eval("WebPassword") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" ValidationGroup="UpdateUser" runat="server" SetFocusOnError="true"
ControlToValidate="txtWebPassword" Display="None" ErrorMessage='<%# Constants.Strings.PasswordRequired %>'></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddWebPassword" ValidationGroup="InsertUser" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvAddPassword" ValidationGroup="InsertUser" runat="server" SetFocusOnError="true"
ControlToValidate="txtAddWebPassword" Display="None" ErrorMessage='<%# Constants.Strings.PasswordRequired %>'></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
http://msdn.microsoft.com/en-us/library/bb426882.aspx#aspnett19_vldcntredtuics_topic7
Note: If you're using ValidationSummaries, you need to add the appropriate ValidationGroup to every ValidationSummary. If you leave this property blank, only controls without a specified ValidationGroup will be listed.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.validationsummary.validationgroup.aspx
I added a RequiredFieldValidator to my InsertItemTemplate, and it seems to be working fine. The problem I am having, however, is that now I cannot do anything else in the ListView (like edit or delete items) UNLESS the required field has a value. Is there some way I can manually do the validation when the user clicks the 'Insert' button on the InsertItemTemplate, or some other little trick I can perform so the user doesn't have to first type in a value just to delete something else in the list?
Thanks
A_Nablsi,
Please provide the code for your solution to turn the Insert New validation controls off when in Edit/Update mode or turn Edit/Update validation controls off when both the Edit and Insert Rows are active at the same time. This code using your notional solution fails with a null reference to the updateButton.
LinkButton updateButton = LVTasks.EditItem.FindControl("UpdateButtonTask") as LinkButton;
updateButton.CausesValidation = false;
The solution that works is adding Validation Groups.
Include ValidationGroup="myVGEdit" with your Validator Control(s) in the EditItemTemplate and your Update button.
Include ValidationGroup="myVGInsert" with your Validator Control(s) in the InsertItemTemplate and your Insert button.
<asp:ListView ID="LVTasks" runat="server"
DataKeyNames="IDTask"
DataSourceID="LDS_LVTasks"
InsertItemPosition="FirstItem"
oniteminserting="LVTasks_ItemInserting"
onitemupdating="LVTasks_ItemUpdating"
onitemcommand="LVTasks_ItemCommand"
>
<EditItemTemplate>
<asp:TextBox ID="TaskUpdateTextBox" runat="server"
Text='<%# Bind("Task") %>'
TextMode="MultiLine" Rows="1" Font-Bold="true" Width="300px"
/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please Set Task title"
ControlToValidate="TaskUpdateTextBox"
ValidationGroup="myVGUpdate"
/>
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CommandArgument='<%#Eval("IDTask") %>'
CommandName="Cancel"
CausesValidation="False"
ToolTip="Cancel - Abort - No Changes"><div class="Cancel"></div></asp:LinkButton>
<asp:LinkButton ID="UpdateButtonTask" runat="server"
CommandArgument='<%#Eval("IDTask") %>'
CommandName="Update"
CausesValidation="True"
ValidationGroup="myVGEdit"
ToolTip="Save Changes - Update"><div class="Update" ></div></asp:LinkButton>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TaskInsertTextBox" runat="server" Text='<%# Bind("Task") %>'
TextMode="MultiLine" Rows="1" Font-Bold="true" Width="300px"
/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please Set Task title"
ControlToValidate="TaskInsertTextBox"
ValidationGroup="myVGInsert"
/>
<asp:LinkButton ID="CancelButton" runat="server"
CommandArgument='<%#Eval("IDTask") %>'
CommandName="Cancel"
CausesValidation="False"><div class="Clear" ></div></asp:LinkButton>
<asp:LinkButton ID="InsertButtonTask" runat="server"
CommandArgument='<%#Eval("IDTask") %>'
CommandName="Insert"
CausesValidation="true"
ValidationGroup="myVGInsert"
><div class="Insert" ></div></asp:LinkButton>
</InsertItemTemplate>
Yes,
set the CausesValidation property to false on the controls you don't want them to trigger the validation.