How to get custom validator event to fire in asp.net? - c#

I am using custom validator tool in asp.net to check whether a text box is blank or not(I did not use requiredfieldvalidator because the text box in question is going to be enabled occasionally).The problem is that the custom validator event in code behind is not firing at all.This is the source code:
<asp:TextBox ID="txtS_rentSDate" runat="server" Font-Names="Bookman Old Style"
Font-Size="Medium" Width="326px"
ontextchanged="txtS_rentSDate_TextChanged"
CausesValidation="True"></asp:TextBox>
<asp:CustomValidator ID="cvRentSDate" runat="server"
ControlToValidate="txtS_rentSDate"
ErrorMessage="Please enter the rent start date"
onservervalidate="cvRentSDate_ServerValidate" ValidateEmptyText="True"
Width="180px"></asp:CustomValidator>
Code behind:
protected void cvRentSDate_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (args.Value.Length > 0);
}
Kindly let me know where I am going wrong and what is the proper way to do it?

<asp:CustomValidator ID="cvRentSDate" runat="server"
ControlToValidate="txtS_rentSDate"
ErrorMessage="Please enter the rent start date"
OnServerValidate="cvRentSDate_ServerValidate" ValidateEmptyText="True"
Width="180px"></asp:CustomValidator>
Try with my above lines. May be you need to use OnServerValidate instead of onservervalidate.

Related

Required Field Validator always shows the error message

I have this code:
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rvFirstName" runat="server"
ErrorMessage="Enter First Name"
ForeColor="Red" ControlToValidate="txtFirstName"
SetFocusOnError="True"></asp:RequiredFieldValidator>
The problem is that the error message shows every time the page loads not only after the submit button has been clicked. I want it to show it only if the user tries click the "Next"(submit) button (how it should work).
If this is relevant: The code above is placed in a UserControl which is included in another UserControl(the "Next" button is here) which is then included in a View of a MultiView.
Any ideas
use causeValidation to false on other buttons.
and display to dynamic.
Display="Dynamic" on require filed validator
<asp:RequiredFieldValidator ID="rvFirstName" runat="server" Display="Dynamic"
ErrorMessage="Enter First Name" ForeColor="Red"
ControlToValidate="txtFirstName" SetFocusOnError="True">
</asp:RequiredFieldValidator>
The best way is set ValidationGroup on Button and RequiredFieldValidator.
please take a look on references below, is it you have something like Page.Isvalid in your page?
References : Required Field Validator, displaying on initial page load
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ShowMessageBox="True" DisplayMode="BulletList"
HeaderText="Validation issues" ShowSummary="False" ValidationGroup="Validation"/>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rvFirstName" runat="server" ErrorMessage="Enter First Name" ForeColor="Red" ControlToValidate="txtFirstName" SetFocusOnError="True" ValidationGroup="Validation"></asp:RequiredFieldValidator>
Add the above code and modify your Required Field Validator
Set 'ValidationGroup' for RequiredFieldValidator and the Next button
Remove the SetFocusOnError="True" and add display="Dynamic" instead of SetFocusOnError="True" in your requiredfieldvalidation and set casevalidtion="false" in your page.
01.If you want to display message in page load. protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Page.Validate();
}
}
Display="Dynamic"

Enable/Disable Required field validator from cs page?

I have two TextBox and two Buttons in my page.
One is hidden and the other one is displayed.
When I click the Button1, it will save data of the two TextBox and will validate each TextBox by the RequiredFieldValidator.
Then when I click Button2, it will just hide itself (Button2) and will show the hidden TextBox.
Both TextBox has RequiredFieldValidator validating against Button1's Event click.
Now my issue is when I simply enter text to the 1st TextBox and click save, the button click is validating the required field for hidden field. I just want to validate the 2 textbox when it is showing.
How can I avoid this?
Well you can simple use the Enabled="false" property of RequiredFieldValidator.
Your markup would look something like this based on your Question.
<asp:TextBox runat="server" ID="tb1"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv1" ControlToValidate="tb1" ErrorMessage="*" ValidationGroup="gvSave">
</asp:RequiredFieldValidator>
<asp:TextBox runat="server" ID="tb2" Visible="false"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="rfv2" ControlToValidate="tb2" ErrorMessage="*" Enabled="false" ValidationGroup="gvSave">
</asp:RequiredFieldValidator>
<asp:Button runat="server" ID="btn1" Text="Save" onclick="btn1_Click" ValidationGroup="gvSave"/>
<asp:Button runat="server" ID="btn2" Text="Show" onclick="btn2_Click" />
And your codebehind like this:
protected void btn2_Click(object sender, EventArgs e)
{
tb2.Visible = true;
rfv2.Enabled = true; // Enables the second requiredfieldvalidator
}
protected void btn1_Click(object sender, EventArgs e)
{
// your Saving code here
}
use the ValidationGroup="group" property to button and assign validation group to text on which you want to validate.
Hope it will help
You can specify CausesValidation="false" for the secondary button, this is less verbose and potentially confusing when validation groups are A) excessive for a single field and B) you have to maintain validation groups when adding further controls (do we put it on the button, the validator, the field and the validation summary? It's not a lot the remember the standard, but less practical when editing.
This is Aspx :
<td align="right">
Cut Type :
</td>
<td class="required">
<telerik:RadComboBox ID="cmbCutType" runat="server" MaxHeight="200px" Width="200px"
Filter="Contains" EnableLoadOnDemand="true" EmptyMessage="Select Cut Type" OnSelectedIndexChanged="cmbCutType_SelectedIndexChanged"
AutoPostBack="true">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" ID="rfvCutType" Display="None" ControlToValidate="cmbCutType" InitialValue=""
ValidationGroup="Save" ErrorMessage="Cut Type is Mandatory"
ForeColor="Red"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="vceCutType" TargetControlID="rfvCutType"
runat="server">
</ajaxToolkit:ValidatorCalloutExtender>
</td>
This is code behind :
protected void btn2_Click(object sender, EventArgs e)
{
rfvCutType.IsValid = false;
}
try this.......
If you wish you use backend validation then check this out, it worked for me.
Requiredfieldvalidator.Enabled = False
Requiredfieldvalidator is an ID.
The project I am working has all the fields visible but based on certain conditions, validation has to be disabled.

Compare fields (validation c#/asp.net)

I'm working on an application with two input fields that's validated in different ways with RequiredFieldValidator, RangeValidator and so on. I need one more validation and that is to check that the number the user writes in input1 isn't bigger than in input2, and here's the question.
Is it possible to use validation controls to compare 2 input fields, or do I need to write code for it? I'm using a ValidationSummary control and of course I want to show all the errors with this. If it isn't possible to use validation controls to compare 2 input fields and I need to write code for this, is it possible to show the error message with the ValidationSummary anyway, and in that case how?
Thanks in advance!
You can use the CompareValidator.
See here for an example.
Use a custom validator control and use the ServerValidate event to return true/false depending on if the check is correct.
The validation summary will pick up that the Page is not valid and display your message.
C#
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (TextBox1.Text.Length > TextBox2.Text.Length)
args.IsValid = false;
else
args.IsValid = true;
}
.aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid Length" Display="None" onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
Have you tried using the CompareValidator?
This allows you to compare 2 input fields and is a standard control as per the Requiredfield and Range validators.
<asp:CompareValidator ControlToCompare="text1" ControlToValidate="text2" ErrorMessage="error" runat="server" Operator="LessThan" Type="Integer" />
bool isLonger(string s1, string s2)
{
return s1.Length > s2.Length ? true : false;
}
returns true if the length if s1 is greater than the length of s2

How to validate expression on button click in asp.net C#

I am making a website and I have made a form fields like email field and validation expressions associated with it. Validation is initiated on text change. But i want it t execute on "submit" button click event.
I have searched but could not locate the solution to my problem. Please tel me why is this happening and how can i make it right. I am new to this web development field, So need help from you guys.
Thanks in advance!!!
Hamad
You could disable showing errors in the validator itself and instead make a validation summary which will be shown only after you click submit.
Like this:
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtEmail" ValidationGroup="vRegister" Display="None" ErrorMessage="Email field cannot be empty"></asp:RequiredFieldValidator>
and then declare a validation summary:
<asp:ValidationSummary runat="server" ID="vSummary" ValidationGroup="vRegister" DisplayMode="BulletList" />
What you should do is change the value of EnableClientScript to false. Then call the validation from your code behind (which should always be done since a user can disable their client side validation anyway. Security rule 1, never trust the client)
EnableClientScript: Gets or sets a value indicating whether client-side validation is enabled.
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server" EnableClientScript="false"
ErrorMessage="*" ControlToValidate="txtName" ></asp:RequiredFieldValidator>
Code Behind:
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Do stuff
}
//No need for else, the validations should display accordingly
}
Additional resources: http://weblogs.asp.net/rajbk/archive/2007/03/15/page-isvalid-and-validate.aspx
Are you simply looking for the validation type controls to validate input?
If so look at the property EnableValidation and set it to true. Doing so will force the validation of the textbox even before the button_Click event can execute.
Try this:
<asp:TextBox ID="txtName" runat="server" Height="23px"
Width="252px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ErrorMessage="*" ControlToValidate="txtName"
ValidationGroup="vadd"></asp:RequiredFieldValidator>
The "Causes Validation" property on the button itself will automatically force your page to meet you validation specifications before firing the rest of the code associated with the button press.
If i have understood your question, you need to create a same validation group for each of the validation control in your aspx page. You also need to have a validation summary with same validation group. And atlast in the submit button in aspx page you have to mention same validation group...

Custom Validator firing but it does not update the ValidationSummary

Hi I am working on a custom form field validator, it seems like the custom validator is working by not allowing it to continue to the next page, but it doesn't update the Validation Summary nor does it display the asterisk and the labels that i've made visable. I also have other validators like RequiredFieldValidator on the same field. My ValidationGroup is set, as is the Text and IsValid. I even wrote and set a dummy client side validation method in javascript as some workarounds suggests.
here is the validation summary code in asp.net
<asp:ValidationSummary ID="ValidatorSummary" runat="server" ValidationGroup="Step2" />
here is the custom validator and the required field one
<asp:CustomValidator ID="AddressVerification" runat="server" ErrorMessage="Please enter a valid address." Display="Dynamic" ValidationGroup="Step2" OnServerValidate="AddressVerification_ServerValidate" ClientValidationFunction="CustomValidatorDummy" Text="*" Enabled="true" EnableClientScript="true"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="RFValidatorHomeAddress" runat="server" ErrorMessage="Please enter home address." Text="*" Display="Dynamic" ValidationGroup="Step2" ControlToValidate="txtHomeAddress"></asp:RequiredFieldValidator>
here is the custom validation method in the code behind
protected void AddressVerification_ServerValidate(object sender, ServerValidateEventArgs e)
{
//lets just say it doesn't validate and sets the IsValid to false
lblUspsValidatorResHomeCity.Visible = true;
lblUspsValidatorResHomeState.Visible = true;
lblUspsValidatorResHomeZip.Visible = true;
e.IsValid = false;
}
please advise, thanks.
EDIT:
Answered - as bitxwise mentioned. the validation summary should be placed inside an update panel as well. Thanks!
Like so:
<asp:UpdatePanel ID="UpdatePanelValidationSummaryHome" ChildrenAsTriggers="false" UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:ValidationSummary ID="AddressHomeValidationSummary" runat="server" ValidationGroup="AddressHomeValidationGroup"
CssClass="errors" />
</ContentTemplate>
and then calling the update:
UpdatePanelValidationSummaryHome.Update();
You seem to be missing ControlToValidate in your declaration of CustomValidator.
EDIT
If your CustomValidator aggregates multiple controls, then try this:
ASPX
<asp:TextBox ID="txtMyTextBox" runat="server" />
<asp:CustomValidator ID="AddressVerification" runat="server"
Display="Dynamic"
ErrorMessage="Please enter a valid address."
OnServerValidate="AddressVerification_ServerValidate"
Text="*"
ValidationGroup="Step2" />
<asp:RequiredFieldValidator ID="rfvAddress" runat="server"
ControlToValidate="txtMyTextBox"
Display="Dynamic"
ErrorMessage="Please enter an address"
Text="*"
ValidationGroup="Step2" />
...
<asp:ValidationSummary ID="ValidatorSummary" runat="server"
ValidationGroup="Step2" />
...
<asp:Button ID="btnCheckAddresses" runat="server"
CausesValidation="true"
Text="Check Addresses"
ValidationGroup="Step2" />
CS
protected void AddressVerification_ServerValidate(object source, ServerValidateEventArgs args) {
args.IsValid = !string.IsNullOrEmpty(txtMyTextBox.Text) && !txtMyTextBox.Text.Contains(' ');
}
Note that the validation group of the control invoking the post back has CausesValidation="true" and has the same ValidationGroup as the validators.
EDIT 2
If your postback control was in the UpdatePanel but the ValidationSummary was not, then the partial postback would not have refreshed the ValidationSummary. Once you removed the postback control from the UpdatePanel, I imagine it would then generate a full postback, which would refresh your ValidationSummary.
I don't know what else is in your UpdatePanel, but many people report having issues with their validators being in UpdatePanel's.
Check out MSDN,
When you use the ValidationSummary
control inside an UpdatePanel control,
make sure that the validator control
and the control it is associated with
are in the same panel. For more
information about using the
UpdatePanel control for partial-page
updates, see Partial-Page Rendering
Overview.
as well as this MSDN blog.
Make sure every control (textbox, checkbox, etc) that is being validated, every RequiredValidator, CustomValidator and ValidationSummary has the same ValidationGroup value.
ie.
<asp:CustomValidator ID="CustomValidator6" runat="server" ErrorMessage="The field is required"
ValidationGroup="myValGroup">*</asp:CustomValidator>
Of course this will only work if all the controls are inside the same panel or parent control.
In my case the validation summary was not showing because the submit button was in a separate update panel.
<Triggers>
<asp:PostBackTrigger ControlID="ButtonSubmit" />
</Triggers>
Once I added the above code the summary appeared.

Categories

Resources