asp:RequiredFieldValidator validation based on conditions - c#

I have validation as below but only like to triggered if the checkbox is ticked.
<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator1"
Text="*"
ErrorMessage="Name is required"
ControlToValidate="TextBox1" />
Can I get it done using asp:RequiredFieldValidator?
I only like to validate if a certain condition matched.
Currently it is validating every time the 'Save' button is clicked.

Use a custom validator instead:
<asp:CustomValidator ID="cv1" runat="server"
ErrorMessage="Name is required"
Text="*"
ControlToValidate="TextBox1"
ValidateEmptyText="True"
ClientValidationFunction="validate" />
and the script (just checking a checkbox and the textbox value as example; you can use custom logic):
<script type="text/javascript">
function validate(s,args){
if(document.getElementById("<%= checkboxId.ClientID %>").checked){
args.IsValid = args.Value != '';
}
else{
args.IsValid = true;
}
}
</script>
This will do the client-side validation. If you need server validation also, add the OnServerValidate attribute, and a handler on code behind. See here for details.

I solved this easily by adding the following javascript on Client side.
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true); or
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);

You can also try this one
protected void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox.Checked)
{
RequiredFieldValidator1.Enabled = true;
RequiredFieldValidator1.ValidationGroup = "anything";
Button1.ValidationGroup = "anything";// your save button
}
else
{
RequiredFieldValidator1.Enabled = false;
RequiredFieldValidator1.ValidationGroup = string.Empty;
Button1.ValidationGroup = string.Empty; // save button
}
}

Try this...
protected void RequiredFieldValidator1_Load(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
RequiredFieldValidator1.Enabled = true;
}
else if (CheckBox1.Checked == false)
{
RequiredFieldValidator1.Enabled = false;
}
}

You can enabled/Disabled the RequiredFieldValidator from the Javascript/jQuery.
For your condition, When Checkbox is checked :- Just call the javascript function to enabled the RequiredFieldValidator and when its Uncheck just disabled the RequiredFieldValidator.
For other Conditions like Dropdown index change, textbox value change and radio button selection change you can call its onchange, onblur, onclick respectively and
After executing the required condition you can Enabled/Disabled the RequiredFieldValidator.
Hope this help you.

Related

Custom Validation doesn't fire

Here are my lines of code:
For the Textbox and the CustomValidator:
<asp:TextBox ID="Edit_Tbox_Email" runat="server" placeholder="Email Address..." CausesValidation="true" ValidationGroup="submission"></asp:TextBox>
<asp:CustomValidator runat="server" ControlToValidate="Edit_Tbox_Email" ID="cv_Email" OnServerValidate="cv_Email_ServerValidate" ErrorMessage="!" data-toggle="tooltip" title="Invalid Input!" ValidationGroup="submission"></asp:CustomValidator>
This is for the Button to allow the user to change his/her email:
<asp:Button ID="Edit_But_Email" runat="server" Text="Change" CssClass="btn btn-small" OnClick="Edit_But_Email_Click" ValidationGroup="submission" CausesValidation="true"/>
On server side:
protected void Edit_But_Email_Click(object sender, EventArgs e)
{
if(Page.IsValid)
Edit_Lab_Email.Text = Edit_Tbox_Email.Text;
}
protected void cv_Email_ServerValidate(object source, ServerValidateEventArgs args)
{
string emailRegex = "^\\w+[\\w-\\.]*\\#\\w+((-\\w+)|(\\w*))\\.[a-z]{2,3}$";
if (Edit_Tbox_Email.Text.Length == 0 || Regex.IsMatch(Edit_Tbox_Email.Text, emailRegex))
{
cv_Email.IsValid = false;
}
}
But the problem here is that cv_Email_ServerValidate() doesn't even fire. Basically, it doesn't validate the Textbox. Also, I don't want to use the RequiredFieldValidator and RegularExpressionValidator. I want to combine their functionalities into just one validator. And as much as possible I would like to use the code behind(c#) only and not by jQuery. Thank You!
Your button have a ValidationGroup but your CustomValidator don't have one. If you want your button to valide it, you must set the same ValidationGroup.
Edit:
You have to set ValidateEmptyText="true" otherwise, it won't validate empty value.

How can I tell which button in a repeater got pressed?

I have the following markup in an .aspx file:
<asp:Repeater ID="ListOfAssignments" runat="server" OnItemDataBound="ListOfAssignments_ItemDataBound">
<ItemTemplate>
<asp:Label ID="AssignmentID" runat="server" Text="Label"></asp:Label>
<br />
<asp:Label ID="PathToFile" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="RemoveAssignment" runat="server" Text="Remove" OnClick="RemoveAssignment_Click"/>
</ItemTemplate>
</asp:Repeater>
There are two labels and a button in a fairly standard repeater control. The repeater is bound to a database, and populates the labels with records from the database.
Here's my problem: I have a click event for each button in the repeater. The RemoveAssignment_Click method is called when the user clicks any of the buttons. In the click event, I want to know the text of the two labels associated with whatever button the user clicked.
What I mean is, in this method:
protected void RemoveAssignment_Click(object sender, EventArgs e)
{
//code goes here
}
I want to be able to know the text of the labels that are adjacent to the button that was clicked. How do I do that?
What you are looking for is the Button.OnCommand Method:
This allows you to create multiple Button controls on a Web page and
programmatically determine which Button control is clicked.
So inside ListOfAssignments_ItemDataBound you'd assign the CommandArgument to the button, where the CommandArgument is the ID of the article to be deleted:
protected void ListOfAssignments_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Button delButton = e.Item.FindControl("RemoveAssignment") as Button;
delButton.CommandArgument = //set to the value of AssignmentID
//rest of your code
}
}
And now your button should say to use your new OnCommand:
<asp:Button ID="RemoveAssignment" OnCommand="RemoveAssignment" runat="server" Text="Remove" />
And then you create the method:
protected void RemoveAssignment(object sender, CommandEventArgs e)
{
int articleIDToDelete = 0;
if (Int32.TryParse((string)e.CommandArgument, out articleIDToDelete))
{
//delete the article with an ID = articleIDToDelete
}
}
You can add CommandName and CommandArgument attributes to the button tag and use them as a hint. And then in your even handler you can do e.CommandName == "xxx" or e.CommandArgument == "xxx". You can also use CommandArgument to pass the actual strings. You just need to bind the data just like you would do with a label, text, etc:
<asp:Button ID="RemoveAssignment" runat="server" CommandArgument='<%#Eval("Label1")+","+ Eval("Label2")%>' Text="Remove" OnClick="RemoveAssignment_Click"/>
Then in the event handler you can do something like:
string[] args = e.CommandArgument.ToString().Split(new char[] {','});
string label1 = args[0];
string label2 = args[1];
This should get you going.
Hm, I know c# and wp but you should try to set a bool and use this logic: if it is false, repeat will continue and if it is true, it'll exit the repeat. try this:
bool exit;
void Button_Click(eventargs stuffy here)
{
exit = true,
}
void Repeat()
{
if (exit == false)
{
Repeat();
//Your code here
}
}

The RequiredFieldValidator for a drop down control inside of user control does not fire

Following is the test scenario for my code.
1) Once the user selects one of the radio buttons on Webpage.aspx, a modal popup extender shows up.
2) A user control (SSL_Ticket.ascx) is defined inside the modal popup window.
3) A RequiredFieldValidator is defined for a drop down list contained inside the user control.
4) If the user selects the "0" value from drop down list, no validation error message is displayed.
Code
Webpage.aspx
<asp:RadioButtonList ID="RadioButtonListForTicket" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="radioButtonListForTicket_OnSelectedIndexChanged">
<asp:ListItem Selected="True">No</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
</asp:RadioButtonList>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderForTicket" runat="server" BackgroundCssClass="popUpStyle"
DropShadow="true" PopupControlID="divTicketPreview" PopupDragHandleControlID="panelDragHandle"
TargetControlID="btnForPopupAppear" CancelControlID="btnForPopupDisappear"/>
....
...
Webpage.aspx.cs
protected void radioButtonListForTicket_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
if (RadioButtonListForTicket.SelectedItem.Text.ToString().Equals("Yes"))
{
// Check if the sites are selected
updateSelectionCount();
updateListOfSites();
if (selectionCount == 0)
{
lblSSLTicketSelection.Text = "Please select a site.";
RadioButtonListForTicket.SelectedValue = "No";
return;
}
else
{
lblSSLTicketSelection.Text = "";
}
....
ModalPopupExtenderForTicket.Show();
}
}
...
SSL_Ticket.ascx
<asp:DropDownList ID="cmbRootCause" runat="server" Width="255px" OnSelectedIndexChanged="cmbRootCause_SelectedIndexChanged" AutoPostBack="true"
CausesValidation="true">
<asp:ListItem Value="0">Select</asp:ListItem>
<asp:ListItem Value="1">Item1</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="reqdFieldForRootCause" runat="server" ControlToValidate="cmbRootCause" InitialValue="Select"
ErrorMessage="Please select root cause" ValidationGroup="validateRootCause" Visible="false" Display="Dynamic" EnableClientScript="true">
</asp:RequiredFieldValidator>
...
SSL_Ticket.ascx.cs
protected void cmbRootCause_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRootCause.SelectedItem.ToString().Equals("Other"))
{
lblcmbRootCause.Text = "";
lblcmbRootCause.Visible = false;
txtRootCauseOther.Visible = true;
}
else if (cmbRootCause.SelectedItem.ToString().Equals("Select"))
{
lblcmbRootCause.Visible = true;
lblcmbRootCause.Text = "Please select root cause";
}
else
{
lblcmbRootCause.Text = "";
lblcmbRootCause.Visible = false;
txtRootCauseOther.Visible = false;
}
}
I did browse through couple of solutions (ValidateProperty, Client-side validation, RangeValidation, etc), but it did not fire validation text.
This did not help - Handling RequiredFieldValidator inside of a User Control
I'd appreciate your help very much.
Thanks!!!
Remove visible = false attribute from required field validator, by default they won't show up in the beginning.
<asp:RequiredFieldValidator ID="reqdFieldForRootCause" runat="server" ControlToValidate="cmbRootCause" InitialValue="Select"
ErrorMessage="Please select root cause" ValidationGroup="validateRootCause" **Visible="false"** Display="Dynamic" EnableClientScript="true">
</asp:RequiredFieldValidator>
Well in your 'RequiredFieldValidator' for your DropDownList you need to remove this:
InitialValue="Select"

Custom validator getting invoked onclick of all controls on the page

i have written a custom validation function to check if a panel is displayed
i want the function to be invoked onclick of NEXT button.
But instead it gets invoked onclick of every button on the page.
Here is the code:
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
and this is the button code onclick of which it should be invoked.
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
if i set Controltovalidate="btnNext" then it again throws me error.
"btnNext cannot be validated".
You need to hook it to the right element.
document.getElementById("btnNext").onclick = function() {
//Do Your Stuff Here
};
Angela
Hey i did a very simple solution to my problem.
first is the java script code that ws getting invoked onclick of evry button on the page.
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
Then on the Next button:
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
and for the rest of buttons i did set causesvalidation=false property. with this the function wwas getting invoked only on Next button

Using validators to ensure that user filled either one of two required fields

I have an ASP.NET form for currency exchange requests. There are two text fields there: amount-source and amount-target.
One of them must be filled and only one.
How to implement this using Validators, if applicable?
You can use Custom Validators for this:
<asp:Textbox id="textbox1" runat="server" />
<asp:CustomValidator id="valCustom" runat="server"
ControlToValidate="textbox1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidate"
ErrorMessage="*You can only enter 1" display="dynamic">*
</asp:CustomValidator>
<asp:Textbox id="textbox2" runat="server" />
<asp:CustomValidator id="valCustom2" runat="server"
ControlToValidate="textbox2"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidate"
ErrorMessage="*You can only enter 1" display="dynamic">*
</asp:CustomValidator>
<script language="Javascript">
function ClientValidate(source, arguments)
{
var tb1 = document.getElementById("<%=textbox1.ClientID %>").value;
var tb2 = document.getElementById("<%=textbox2.ClientID %>").value;
if (tb1 && tb2 || (!tb1 && !tb2)){
arguments.IsValid = false;
} else {
arguments.IsValid = true;
}
}
</script>
Server-side:
protected void ServerValidate(object sender, ServerValidateEventArgs args)
{
if(string.isNullOrEmpty(textbox1.Text) && string.isNullOrEmpty(textbox2.Text))
args.IsValid = false;
else if(!string.isNullOrEmpty(textbox1.Text) && !string.isNullOrEmpty(textbox2.Text))
args.IsValid = false;
else
args.IsValid = true;
}
If you're using jQuery please comment...this can all be much cleaner.
I would implement a custom Validator and decorate both TextBoxes with it. If both are filled, then both are in a error state.

Categories