Validate two controls (CustomValidator) - c#

Before submitting the form I need to test if the sum ( txtA + txtB) is greater than 100. Is it possible to do this with a CustomValidator, because I don't know if I can choose the 2 textbox in controltovalidate
<asp:TextBox ID="txtA" runat="server"></asp:TextBox>
<asp:TextBox ID="txtB" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator" />
<asp:Button ID="Button1" runat="server" Text="Button" />
Thanks.

you can do as :
<asp:TextBox ID="txtA" runat="server" />
<asp:TextBox ID="txtB" runat="server" />
<asp:CustomValidator ID="CV1"runat="server"
OnServerValidate="ServerValidation"
ErrorMessage="Sum is less than 100" />
codebehind :
protected void ServerValidation(object source, ServerValidateEventArgs args)
{
args.IsValid = int.Parse(txtA.Text)+ int.Parse(txtB.Text) >100;
}

When you drop a custom validation in your page, you can link the validator to a control, but if you want to perform multiple validations over more than one control, you need to include the following attribute
OnServerValidate="MyMethodOnServerSide"
and define that method on the server side
protected void MyMethodOnServerSide(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrEmpty(mytxt1.Text) &&
string.IsNullOrEmpty(mytxt2.Text))
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
just asign the args.IsValid property to the value you need. On the other hand the validation is done before you load the page, so if you clicked a button that performs an action like reading values from the DB in case everything is correct, on that action you need to include the following check.
protected void cmdSearch_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
LoadDataFromDB();
}
}
When args.IsValid is false then Page.IsValid is false too. Hope this helps

You need to add another control, <asp:HiddenField> and then leverage jQuery to set the value of that control. It might look something like this:
MARKUP
<asp:HiddenField ID="SumOfValues" />
<asp:CustomValidator ID="CustomValidator2"
runat="server"
ErrorMessage="CustomValidator"
ControlToValidate="SumOfValues" />
JQUERY
$(document).ready(function() {
$('#txtA').change(sumValues);
$('#txtB').change(sumValues);
});
function sumValues() {
var val1 = $('txtA').value();
if (val1 === undefined) { val1 = 0; }
var val2 = $('txtB').value();
if (val2 === undefined) { val2 = 0; }
$('#SumOfValues').value(val1 + val2);
}
and that should allow you validate that hidden control. However, one thing you'll need to make sure to do on all three controls is leverage ClientIDMode and set it to Static so that the names are exactly what you specify in the markup when they get to the page.

Related

Check if atleast one textbox value is not null or zero in c#?

I have multiple TextBox on my page. I want to validate if atleast one TextBox value is not null or 0 in asp.net webform.
The TextBox id's are from txtvalue1 to txtvalue20. I tried manually but instead of doing manually, for looping could be the best option I think. How do I do that? Thanks!
Use reflection and do something like this (untested).
bool areOneOrMoreFieldsEmpty()
{
var textboxControls = GetType().GetFields().Where(field => field.Name.StartsWith("txtvalue");
foreach(var control in textboxControls)
{
var textValueProperty = control.GetProperty(nameof(TextBoxControl.Text));
var stringValue = textValueProperty.GetValue(this, null) as string;
if (string.IsNullOrEmpty(stringValue) || stringValue == "0")
{
return false;
}
}
return true;
}
You can use customvalidator:
In .aspx:
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Text must not be null or 0" ControlToValidate="txt1" OnServerValidate="TextBoxValidate" ForeColor="Red" />
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Text must not be null or 0" ControlToValidate="txt2" OnServerValidate="TextBoxValidate" ForeColor="Red" />
<asp:TextBox ID="txt3" runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" ErrorMessage="Text must not be null or 0" ControlToValidate="txt3" OnServerValidate="TextBoxValidate" ForeColor="Red"/>
<asp:Button ID="btnDoSomething" runat="server" Text="Do something" OnClick="btnDoSomething_Click" />
In .cs:
protected void btnDoSomething_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
//Do something
}
protected void TextBoxValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (args.Value != null && args.Value != "0");
}
To loop through all buttons knowing just their names, you would have to use reflection, which can be cumbersome - but that's one direction you can research.
Other option is to have collection which you can iterate over:
Button[] myButtons = new Button[]{txtvalue1, ..., txtvalue20};
foreach(var button in myButtons)
{
// do operations here..
}

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

What is the best way to validate that a specific option has been selected in an asp:ListBox?

I have an asp:ListBox that contains multiple values. A user is required to always select one specific item in this box as well as optionally selecting others.
What is the best way to do this?
Thanks in advance!
I think non of the ASP.Net validators fits your requirement out-of-the-box, what you need is to use the CustomValdiator and write server and client code to perform your validation
Example:
ASPX
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function clientValidate(sender, args) {
args.IsValid = false;
$("#" + sender.controltovalidate + " option:selected").each(function (index, item) {
if ($(this).text() == "QuestionText1") {
args.IsValid = true;
return;
}
});
}
</script>
<asp:ListBox runat="server"
SelectionMode="Multiple" ID="lb" AppendDataBoundItems="false"
DataTextField="QuestionText" DataValueField="ID"
>
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
</asp:ListBox>
<br />
<br />
<asp:CustomValidator ErrorMessage="errormessage" ControlToValidate="lb"
ClientValidationFunction="clientValidate"
OnServerValidate="cv_ServerValidate"
runat="server" ID="cv" />
<asp:Button Text="text" runat="server" />
Code Behind
protected void cv_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = false;
foreach (ListItem item in this.lb.Items)
{
if (item.Selected)
{
if (item.Text.ToLower().Trim() == "questiontext1")
{
e.IsValid = true;
break;
}
}
}
}
What I would do is do some javascript validation on submit of the form and then do server side validation to make sure that what they submitted is valid.
You can also accomplish this with a custom validation control and then just check to make sure that the page is valid on post back.

How to get ControlToValidate control inside validation function when a validation function is used for multiple controls

Ok,
This seems straight forward but I am having trouble finding the solution.
I have 10 PeopleEditor controls. Each one of the PeopleEditor controls has a CustomValidator and the ControlToValidate property is set to that specific PeopleEditor control. I assign a function to the control based on criteria.
It is possible that the same validation function is assigned to multiple CustomValidators which in turn means the function needs to know which ControlToValidate control it is validating.
Is this clear?
The question is:
How do I reference the control from the ControlToValidate property in the validation function server side c# code?
Here are similar issues but they reference client side or inline validation:
How to get the 'controlToValidate' property on ClientValidationFunction? and
Extract value from control in ControlToValidate property in a CustomValidator control?
UPDATE:
I have 10 of these in the .aspx page:
<asp:Label ID="lblPeople0" runat="server" />
<SharePoint:PeopleEditor ID="edtPeople0" SelectionSet="User,SecGroup" AutoPostBack="false" CausesValidation="false" PlaceButtonsUnderEntityEditor="false" Rows="3" AllowEmpty="true" ValidatorVisible="true" runat="server" MultiSelect="true" MaximumEntities="100" ShowCreateButtonInActiveDirectoryAccountCreationMode="true" />
<asp:CustomValidator id="vldPeople0" display="Dynamic" runat="server" ErrorMessage="Error Message." ControlToValidate="edtPeople0" />
In the .aspx.cs page, I assign the validating function like this:
vldPeople0.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(validate_ThisAndThat);
Then, I have this for the function and need to get the ControlToValidate in order get the ResolvedEntities from it.
/// <summary>
/// Validation function.
/// </summary>
private void validate_ThisAndThat(Object source, ServerValidateEventArgs args)
{
foreach (PickerEntity entity in (ControlToValidate).ResolvedEntities)
{
String tmpPrincipalType = (entity.EntityData["PrincipalType"]).ToString();
if (tmpPrincipalType == "User")
{
if ((entity.EntityData["DisplayName"]).ToString().Contains("aString"))
{
args.IsValid = false;
}
}
}
}
Ok, so the key was to assign an attribute to the CustomValidator...
<asp:Label ID="lblPeople0" runat="server" />
<SharePoint:PeopleEditor ID="edtPeople0" SelectionSet="User,SecGroup" AutoPostBack="false" CausesValidation="false" PlaceButtonsUnderEntityEditor="false" Rows="3" AllowEmpty="true" ValidatorVisible="true" runat="server" MultiSelect="true" MaximumEntities="100" ShowCreateButtonInActiveDirectoryAccountCreationMode="true" />
<asp:CustomValidator id="vldPeople0" display="Dynamic" runat="server" ErrorMessage="Error Message." ControlToValidate="edtPeople0" />
In the .aspx.cs page, I assign the validating function like this:
vldPeople0.ServerValidate += new System.Web.UI.WebControls.ServerValidateEventHandler(validate_ThisAndThat);
vldPeople0.Attributes.Add("peopleEditor", "edtPeople0");
Then, I have this for the function.
private void validate_ThisAndThat(Object source, ServerValidateEventArgs args)
{
CustomValidator thisValidator = (CustomValidator) source;
string strPeopleEditor = (string)thisValidator.Attributes["peopleEditor"];
PeopleEditor peopleEditor = (PeopleEditor)panel1.FindControl(strPeopleEditor);
foreach (PickerEntity entity in peopleEditor.ResolvedEntities)
{
String tmpPrincipalType = (entity.EntityData["PrincipalType"]).ToString();
if (tmpPrincipalType == "User")
{
if ((entity.EntityData["DisplayName"]).ToString().Contains("aString"))
{
args.IsValid = false;
}
}
}
}
Yes, it's possible to do. The OnServerValidate definition can point to the same method (handler). You can cast the sender of the ServerValidateEventArgs to find the object type and ID. Alternatively, give each validator its own callback, and define a central set of validation methods called from each of the callbacks. This way, the logic is in common methods is called for the appropriate handler.
HTH.

Validation Ignored with PostBackUrl or Response.Redirect Using C#

I have a form with some custom validation. There is a button on the form that should take the user to a 'confirm page' to show all the details of an order.
On-Page Validation
<asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName"
runat="server" CssClass="txtbxln required"></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorBillLN" runat="server"
ControlToValidate="txtBillingLastName"
OnServerValidate="CustomValidatorBillLN_ServerValidate"
ValidateEmptyText="True">
</asp:CustomValidator>
Validator code behind
protected void CustomValidatorBillLN_ServerValidate(object sender, ServerValidateEventArgs args)
{
args.IsValid = isValid(txtBillingLastName);
}
However, if I add PostBackUrl or Response.Redirect to the button onclick method, all the validation controls are ignored.
I could call all the validation methods with the onclick method, but that seems a less than an elegant solution.
I've tried setting CausesValidation=False with no luck.
Any suggestions?
Of course that validation IS ignored if you redirect unconditionally. You should call this.IsValid before you redirect like
protected btRedirect_Click( object sender, EventArgs e )
{
if ( this.IsValid )
Response.Redirect( ... );
}
Check this code
void ValidateBtn_OnClick(object sender, EventArgs e)
{
// Display whether the page passed validation.
if (Page.IsValid)
{
Message.Text = "Page is valid.";
}
else
{
Message.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i%2) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
And Html side code
<form id="Form1" runat="server">
<h3>CustomValidator ServerValidate Example</h3>
<asp:Label id="Message"
Text="Enter an even number:"
Font-Name="Verdana"
Font-Size="10pt"
runat="server"/>
<p>
<asp:TextBox id="Text1"
runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<p>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
For further information check Custom validator
Hope my answer help you to solve your problem.

Categories

Resources