How do you reenable a validation control w/o it simultaneously performing an immediate validation? - asp.net

When I called this function to enable a validator from client javascript:
`ValidatorEnable(document.getElementById('<%=valPassportOtherText.ClientID%>'), true); //enable` validation control
the required validation control immediately performed it validation, found the value in the associated text box blank and set focus to the textbox (because SetFocusOnError was set to true). As a result, the side effect was that focus was shifted to the control that was associated with the Validation control, i teh example, txtSpecifyOccupation.
<asp:TextBox ID="txtSpecifyOccupation" runat="server" AutoCompleteType="Disabled"
CssClass="DefaultTextBox DefaultWidth" MaxLength="24" Rows="2"></asp:TextBox>
<asp:RequiredFieldValidator ID="valSpecifyOccupation" runat="server" ControlToValidate="txtSpecifyOccupation"
ErrorMessage="1.14b Please specify your <b>Occupation</b>"
SetFocusOnError="True"> Required</asp:RequiredFieldValidator>
Perhaps there is a way to enable the (required) validator without having it simultaneously perform the validation (at least until the user has tabbed off of it?)
I'd like validation of the txtSpecifyOccupation textbox to occur only on a Page submit or when the user has tabbed of the required txtSpecifyoccupation textbox.
How can I achieve this?

Don't call the ValidatorEnable method. Instead, get a reference to teh validation control and simply set its "enabled" property as desired.
To clear the validation control's error text, set the innerText property to "".

Related

Why does CustomValidator fire on textbox's onblur

I am building a CustomValidator to handle my own application's logic on time fields ("09:00", "15:35", ...) but I am stumbling on a behaviour that I haven't found any explanation for online.
My focus right now is the validation logic that gets executed client-side.
The problem is, as said in the title, that, if and only if I set the ControlToValidate property in the Validator with the ID of the textbox I am validating, the validation gets fired as soon as focus leaves the textbox; it even fires before the onblur event, which is absolutely detrimental for me, since I am using the onblur event to standardize the time formats (eg "9:00" -> "09:00", "11.45" -> "11:45") and thus, the validation logic potentially receives an incorrect value. If, on the other hand, the ControlToValidate property remains blank, the ClientValidationFunction is fired only on a submit/postback.
The only related answer I've found is this https://stackoverflow.com/a/8649697/450684, but still, to me it makes no sense at all. Why should the presence of a ControlToValidate indicate that I want client-side validation to execute before onblur? I don't want it! Is there any way to supress this behaviour?
Here is an example page:
<asp:TextBox runat="server" AutoPostBack="false" ID="txtBox1" onblur="FormatText(this);" />
<asp:CustomValidator runat="server" ID="CV1" ControlToValidate="txtBox1" ClientValidationFunction="Test1" />
<asp:CustomValidator runat="server" ID="CV2" ClientValidationFunction="Test2" />
<asp:Button ID="btn1" Text="postback" runat="server" OnClick="btn1_Click" />
<asp:Label ID="lbl1" runat="server" />
<script type="text/javascript">
function FormatText(txtBox1)
{
alert('FormatText');
}
function Test1(val, args)
{
alert('Test1');
}
function Test2(val, args)
{
alert('Test2');
}</script>
What I want is both Test1 and Test2 to execute only on btn1's click; instead on txtBox1's onblur event I get Test1 and FormatText executing in this order
ASP.NET's client validation was really fun for me to write and study, don't let this ruin everything :-)
Thx
PS: .NET framework's version is 4.0. Plus, the server-side language is C#, if it matters
I think what is going on is this:
The standard behavior for ASP.NET client-side validation is to validate when the field is exited. That's an observation, not a reference to a published standard (although there may be one.) The out-of-the-box validators all behave this way. All of them require specifying a particular field to validate.
The custom validator allows you to validate a single control (by specifying it with ControlToValidate), or lets you validate a combination of controls, in which case you set ControlToValidate to an empty string. Unless things have changed, you do have to specify it; if you omit the attribute, no validation will occur.
So ... if you specify a control to validate, the custom validator behaves like every other validator and reacts to the user exiting the field. If you don't specify a control to validate, it doesn't know what controls you're interested in, and doesn't do that.
You may be able to work around this by writing a truly custom validator: inherit from BaseValidator. That can actually be a lot of fun.
How to manage events of validation for your control.
You can remove ControlToValidate property from your validator and bind validation for your textbox on textbox event as you wish. You can add some function logic before or after validation also. On button click event validation stay the same without change.
function BindValidation(){$('#txtBox1').on('blur keyup change',function(){ValidatorValidate($('#CV1').get(0));});}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(BindValidation);
//validation function example for CV1 validator
function Test1(val, args)
{
args.IsValid=$('#txtBox1').val().length>0&&$('#txtBox1').val().match(/^\s+$/g)==null;
}

Disable Validation controls in asp.net pages

My asp.net page has multiple text-boxes and DropDownLists that all have required-field validators.
My site also has multiple pages that you can move between with the click of a button. (All pages have all the buttons) When a page loads and decide I want to go to a different page without entering information into the form, I click a button to move to a separate page and the validation pops up and I can't change the page, it stops me every time?
Any ideas on how to stop this?
I know you already found a solution, but I just wanted to throw in another method for people to see.
When using validators it is common practice to use ValidationGroups. When a validator belongs to a ValidationGroup, it is only triggered by another control in the validation group. For example:
<asp:TextBox ID="NameBox" runat="server"/>
<asp:RequiredFieldValidator ID="NameVal" ControlToValidate="NameBox"
ValidationGroup="ValSubmit" runat="server"/>
//...More input fields and validators...
<asp:Button ID="SubmitButton" ValidationGroup="ValSubmit" runat="server"/>
Using this method any validators with the "ValSubmit" ValidationGroup will be triggered only by the SubmitButton and not by other controls. Now you don't have to put CausesValidation="false" on EVERYTHING else that causes a postback.
As everyone else had mentioned, set the CausesValidation property to false.
<asp:Button ID="MyButton" Text="Go Back" CausesValidation="False" />
This is straight from the Microsoft Help Page:
By default, page validation is performed when a Button control is clicked. Page validation determines whether the input controls associated with a validation control on the page all pass the validation rules specified by the validation control.
You can specify or determine whether validation is performed on both the client and the server when a Button control is clicked by using the CausesValidation property. To prevent validation from being performed, set the CausesValidation property to false.
Note:
You should set the CausesValidation property to false when you are using the PostBackUrl property to post back to a different page. You should explicitly check validation when posting back to a different page. For an example, see the Remarks section of the PostBackUrl property.
This property is commonly set to false for a reset or clear button to prevent validation from being performed when the button is clicked.
When the value of the CausesValidation property is set to true, you can also use the ValidationGroup property to specify the name of the validation group for which the Button control causes validation.
set property CausesValidation = "false" to the buttons where you don't want to trigger validation
CausesValidation="false" on the button ;)
<asp:Button CausesValidation="True|False" />
Gets or sets a value indicating whether validation is performed when the Button control is clicked.
read more about Button.CausesValidation Property

Server side validation

I am having an issue with the requiredfieldvalidator control not working on an ASP.net page. I have completed the attributes of that field properly, but when I test it, the postback is allowed to happen even if the field in question is blank.
So I want to do server side validation instead. What is the best way to do that? In the event that caused the postback? Also, if I find out the field is blank, how do I get the user back to the screen with all other values they placed on other fields intact and a message saying "This field cannot be blank".
EDIT:
This is the code:
<asp:TextBox ID="fName" TabIndex="1" runat="server" Width="221px" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="FNameRequiredFieldValidator" runat="server" ControlToValidate="fName" InitialValue="" ErrorMessage="Filter Name cannot be blank." ToolTip="Filter Name cannot be blank.">*</asp:RequiredFieldValidator>
You need to provide the markup for your Button / Link control as well.
The 'CausesValidation' attribute is not supposed to be used on TextBox controls.
The button you click needs to have that attribute set to "True".
Please provide that markup and then I can advise on the alternate server side validation.
To enable Client-side Validation, set the EnableClientScript="true" on the RequiredFieldValidator.
You should also always validate on the server side too. But the RequiredFieldValidator doesn't let you do any special-handling server-side. Just check if Page.IsValid(). This will return false if the field is not supplied.
If you want to do custom validation, use a CustomValidator.

Two ASP.net buttons on same page problem?

I have two asp buttons on a single page. In the following format
textbox1
required field validator1
button1
textbox2
required filed validator2
button2
if I keep cause validation on both buttons true, then its not firing the server side click event, but I am able to validate these text boxes using required field validators.
If I keep this cause validation on both buttons false, its firing the server side click event, but I am not able to validate these textboxes using required filed validators
Can you please tell me the best solution
Thanks
CausesValidation should be true on both.
What you need to do is set ValidationGroup Button1Validation on the textbox1 validator and button1. Set a ValidationGroup of Button2Validation on the textbox2 validator and button2.
Validation groups separate validation rules into groups so that the groups don't overlap and interfere with each other.
The default behavior of the RequiredFieldValidator is that when you don't insert something into the textbox to which it's coupled, and client side validation is turned on (defaults to true), then it won't posback and as such the server side event never gets hit.
You can turn off the client side validation on the validator control by setting the property EnableClientScript to false:
<asp:RequiredFieldValidator ID="TextBoxRequiredValidator"
ControlToValidate="NumberTextBox"
EnableClientScript="False"
Display="Dynamic"
ErrorMessage="Please enter a value."
Text="*"
runat="server"/>
Taken from the MSDN documentation.

ASP.NET Custom Validator Error Message: Control referenced by the property cannot be validated

I use ASP.NET and have a Button and a CustomValidator, which has to validate
the button.
<asp:Button ID="saveButton" runat="server" OnClick="SaveButton_Click" Text="Speichern"
CausesValidation="true"/>
<asp:CustomValidator runat="server" ID="saveCValidator" Display="Static"
OnServerValidate="EditPriceCValidator_ServerValidate"
ControlToValidate="saveButton" ErrorMessage="">
When loading the page, I receive the error message:
"Control 'saveButton' referenced by
the ControlToValidate property of
'saveCValidator' cannot be validated."
What might be the problem? I searched on the net, but this didnĀ“t help much.
AFAIK, ControlToValidate property should point to input control or left blank for the CustomValidator control.
A reference from MSDN:
Use the ControlToValidate property to
specify the input control to validate.
This property must be set to the ID of
an input control for all validation
controls except the CustomValidator
control, which can be left blank. If
you do not specify a valid input
control, an exception will be thrown
when the page is rendered. The ID must
refer to a control within the same
container as the validation control.
It must be in the same page or user
control, or it must be in the same
template of a templated control.
The standard controls that can be
validated are:
System.Web.UI.WebControls.DropDownList
System.Web.UI.WebControls.FileUpload
System.Web.UI.WebControls.ListBox
System.Web.UI.WebControls.RadioButtonList
System.Web.UI.WebControls.TextBox
System.Web.UI.HtmlControls.HtmlInputFile
System.Web.UI.HtmlControls.HtmlInputPassword
System.Web.UI.HtmlControls.HtmlInputText
System.Web.UI.HtmlControls.HtmlSelect
System.Web.UI.HtmlControls.HtmlTextArea
You can only use a CustomValidator against Input controls that accept user input:
Client-side validation enhances the
validation process by checking user
input before it is sent to the server.
What you want to do is look here at Button Controls and Validation.

Resources