ValidatorEnable is not defined - asp.net

I am trying to enable and disable a required field validator using javascript but keep getting the error message ValidatorEnable is not defined. PLease find code below, any help would be great.
ASP.Net
<asp:RequiredFieldValidator EnableClientScript="True" Display="None" ID="rfvMostRecentEmployer" ControlToValidate="txtMostRecentEmployer" runat="server" ErrorMessage="Most recent employer title is a required field"></asp:RequiredFieldValidator>
Javascript
var validatorMostRecentEmployer = document.getElementById('<%= rfvMostRecentEmployer.ClientID %>');
ValidatorEnable(validatorMostRecentEmployer, !hasCv);
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
rblCV.Attributes.Add("onClick", string.Format("ShowCvOptions();"));
...
}

Make sure that function ValidatorEnable is placed before calling from any other place.

It could be that you are trying to run the JavaScript code before the asp.net validator code has been included.
If you are using jQuery then try wrapping the code in:
$(document).ready(function () {
var validatorMostRecentEmployer = document.getElementById('<% =rfvMostRecentEmployer.ClientID %>');
ValidatorEnable(validatorMostRecentEmployer, !hasCv);
});
(I also incorporated Ashwin's advice which is the correct way to reference asp.net controls from JavaScript)

ClientID could be the problem.
var validatorMostRecentEmployer = document.getElementById('<% =rfvMostRecentEmployer.ClientID %>');
ValidatorEnable(validatorMostRecentEmployer, !hasCv);
UPDATE Not an elegant solution though but it works, if nothing does.
function disableValidator()
{
var myval = document.getElememtById('<% =rfvMostRecentEmployer.ClientID %>');
myval.style.cssText="";
myval.style.display='none';
myval.style.accelerator=true;
}

After digging through the server side code I found the following code that was disabling the client side script and must have been stopping it getting registered:
//Clear client side validators
foreach (BaseValidator bv in Page.Validators)
{
bv.EnableClientScript = false;
}
Thanks to everyone who helped out with this.

Related

ClientScript.RegisterClientScriptBlock not working

I have a popup in my page which I am trying to show on dropdownlist selected index changed event.
Here is register statement
ClientScript.RegisterClientScriptBlock(GetType(),"id", "ShowApplicationPopUp()",true);
Here is my javascript function
function ShowApplicationPopUp() {
$('#NewCustomerMask').show("slow");
$('#NewCustomerApplicationPopUp').show("slow");
}
Both of my divs are initially hidden by using display:none; statement.
The problem is when my dropdownlist is changed the popup is not seen at all.I tried putting an alert statement to check if the function is called , and the alert statement is fired.Any ideas as to what I am doing wrong.
Any suggestions are welcome.
Thanks.
When you use RegisterClientScriptBlock the Javascript code is inserted early in the page, so it will run before the elements are loaded.
Use RegisterStartupScript instead, which places the code at the end of the form.
I too could not get this code to work but thanks to the above I now have working code. Note, I have a linkbutton inside an Ajax Update Panel.
in my code behind aspx.cs page is:
protected void OpenButton_Click(object s, EventArgs e)
{
// open new window
string httpLink = "../newWindow.aspx";
ScriptManager.RegisterStartupScript(this, GetType(), "script", "openWindow('" + httpLink + "');", true);
}
in my apsx page is first the link to jQuery source, then second the JavaScript for the openWindow function:
<script src="../js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
function openWindow(url) {
var w = window.open(url, '', 'width=1000,height=1000,toolbar=0,status=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1');
w.focus();
}
</script>
and the link that makes it all happen:
<asp:LinkButton Text="Open New Window" ID="LnkBtn" OnClick="OpenButton_Click" runat="server" EnableViewState="False" BorderStyle="None"></asp:LinkButton>
Im not a jQuery expert and must attribute some of this to the following blog:
https://blog.yaplex.com/asp-net/open-new-window-from-code-behind-in-asp-net/

Jquery Asp.net button disable

html code:
<asp:Button runat="server" ID="btnTest" Text="Test" OnClick="btnTest_Click" />
Jquery Code:
$('[id$=btnTest]').click(function(){
$('[id$=btnTest]').attr('disabled', 'true');
});
CodeBehind:
protected void btnTest_Click(object sender, EventArgs e)
{
//here not come.
}
Code Behind btnTest event not work ?
I think that making the button disabled in the click event handler is preventing the postback. Try executing the disabling code after some time:
$('[id$=btnTest]').click(function(){
var button = this;
setTimeout(function() {
$(button).attr('disabled', 'disabled');
}, 100);
});
Try to use jQuery class selector:
Add CssClass="MyButton" to your ASP.NET button;
Use this selector in jQuery
Set disabled="disabled" attribute on click
jQuery:
$('button.MyButton').click(function(){
$(this).attr('disabled', 'disabled');
});
The sample code is using the ends-with selector. There is no mistake in selector.
you just need to change the code like this
$('[id$=btnTest]').click(function () {
$('[id$=btnTest]').attr('disabled', true);
});
I have tested this and works fine without any issues.
I can fix your problems:$(".classButton").prop('disabled','disabled');
and remove disabled: $(".classButton").prop('disabled', '');
Wouldn't you just need to do the following:
btnTest.Enabled = False;
in the code-behind file? This will cause a postback but it should work.
It wouldn't work because the generated HTML id is different than the ASP.NET id.
So btnTest will be rendered as another Id.
A quick dirty way is to to run the page, view the HTML source and locate the button's generated Id and pass it as an arugment in the jQuery function.
A better way is to generate the jQuery function through code behind:
Literal1.Text = "$('[id$=" + btnTest.ClientId + "]').click(function(
{$(this).attr('disabled', 'disabled');});";
Edit:
Also I couldn't help but realize that your OnClick attribute should point to btnTest_Click and not btn_Click

How to set Page.IsValid in ASP.Net

When the page class property IsValid is read only, how can I set it using my own validation method?
So far all I've been able to do is set this property by calling Page.Validate().
How can I write my own functionality that will change the IsValid property just like Page.Validate()?
You don't set IsValid directly instead you call Validate() method of the Page object. If you have your custom validation methods then you need to use CustomValidator object and set that function in its server side validation property.
<asp:CustomValidator ID="YourValidator" runat="server" SetFocusOnError="true"
ControlToValidate="YourControl"
ClientValidationFunction="YOUR_JAVASCRIPT_FUNCTION"
OnServerValidate="YOUR_SERVER_VALIDATION_FUNCTION" Text="*" />
I know this is old, but, I needed to do something similar, basically forcing the IsValid property to false (don't ask why). Here is what I did basically (what you see here is my proof of concept):
Added this to the .aspx page:
<asp:TextBox ID="txtDummy" runat="server" Visible="false" />
<asp:RangeValidator ID="rvDummy" ControlToValidate="txtDummy" runat="server" MinimumValue="1" MaximumValue="2" />
And then I added this to the code behind:
bool makeMyPageInvalid = true;
if (makeMyPageInvalid)
txtDummy.Text = "0";
Page.Validate();
if (Page.IsValid)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "test", "alert('valid');", true);
else
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "test", "alert('not valid');", true);
You can see that this only allows you to force the page validation to an invalid state. You can use any validator or reason to set this. Hope this helps someone!
The IsValid property is read-only because it is intended for use with server and client-side validators like the RequiredFieldValidator and RegularExpressionValidator. It's read-only because you can't force a page to be valid programmatically. "Valid" in this context means all the validators on the page evaluate to true.
If you feel like using some JavaScript you can do it in the client-side by modifying the variable Page_IsValid like this:
function pageLoad() {
Page_IsValid = false;
}
I use this just in case someone clicks the submit button w/o entering data. Then I can display an alert like this:
function valid() {
if (!Page_IsValid) {
alert("Some Questions Remain Unanswered and are Marked with a Red Asterisc. ( * )");
}
(at the beginning I thought 'who would submit a form w/o data' but sooner rather than later I realized it happens)
This is a really old question, but it came up in a search so I thought I'd add my answer to it. First, create an extension method in one of your helper classes.
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
Now in your code behind file, loop over every validator on the page that is not validating.
foreach (var validator in Page.GetAllControlsOfType<BaseValidator>().Where(w => !w.IsValid))
{
validator.IsValid = true;
}

Bug in HTML Editor in ASP.net Ajax toolkit

I'm trying to validate the content of the HTML Editor using an ASP.net custom validator control. The idea is to check that some content has been input - the same way a required field validator works.
In the ClientValidationFunction="SomeFunction" I reference this function:
function SomeFunction(source, args)
{
var editor = $find("<%=htmlEditor.ClientID%>");
var content = editor.get_content();
var isValid = content.length > 0;
editor.set_content(content);
args.IsValid = isValid;
}
The reason that I set the content after getting it, is that this is a hack to get the content to re-register in the editor. For some reason, if I don't reset the content on the second attempt to postback - once it's been validated - the empty content, from the first attempt, gets posted back instead of the valid content.
Does anyone know either how to check the content of the HTML Editor, without having to reset the content? Or, if it is reset using set_content(), without the font size and font style menus being de-activated?
OK, solved this one by updating to the latest release (Sept 2009) of the Ajax Toolkit.
The set_content() hack is no longer necessary. Just remove this from the above javascript code and the custom validator will work. The HTML Editor now passes through the updated content to the server: "Woohoo!"
Thanks to the guys at Obout for fixing the bug! :-)
As I said in my previous post, you shouldn't need the set_content hack. This is my code, which I use to validate that the editor is not empty:
<asp:CustomValidator
CssClass="errorMessage"
ID="HtmlEditorValidator"
runat="server"
ErrorMessage="Release Note cannot be empty"
Display="None"
ControlToValidate="radEditor"
EnableClientScript="true"
ClientValidationFunction ="checkEditorNotEmpty"
OnServerValidate="CheckEditorNotEmptyServerSide"
ValidateEmptyText="true">
</asp:CustomValidator>
function checkEditorNotEmpty(source, args)
{
var editor = $find("<%=radEditor.ClientID%>");
var cont = editor.get_text();
var isValid = cont.length > 0;
args.IsValid = isValid;
}
//In the code behind:
protected void CheckEditorNotEmptyServerSide(object sender, ServerValidateEventArgs args)
{
bool valid = args.Value.Length > 0;
args.IsValid = valid;
}
This works with the September release, I'm hoping they haven't missed out the bug fix in the Novemeber release: that would be very odd.
HTH

Check what control initiated AJAX Request

asp.net 2.0 / jQuery / AJAX
<script type="text/javascript">
//updated to show proper method signature
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(hideMessage);
function hideMessage(sender, args)
{
var ctl = args.get_postBackElement();
//check if ctl is the disired control
//hide user notification message
}
</script>
i have several controls on the page that might initiate the AJAX request, but i only want my js to fire when i click one particular button. how do i check what control initiated the request so i can fire JS accordingly.
EDIT: I worked around it, but I'd still like to know if I can do it this way.
Clarification: I can't call the JS from onclick event, because the page is inside of the UpdatePanel, and i only want the JS to execute when AJAX Request ends and it was triggered by one particular button on the page. On server side, i set the myLabel.Text to some text, and then js checks if the $(myLabel.CliendID)'s innerHTML is not blank and fires the js. checking the innerHTML is my work-around since i can't figure out how to check the "sender" of AJAX Request. Hope this makes more sense now.
edit2: I've read some documentation, and turns out you CAN check the "sender" control.
Thank you.
This is what I am doing in my code to identify what control has initialized the request. All javascript code.
function pageLoad() {
if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequest);
}
}
function endRequestHandler(sender, args) {
if (sender._postBackSettings.sourceElement.id == '<%= gvResults.ClientID %>') {
//do something because of this...
}
}
function initializeRequest(sender, args) {
if (CheckForSessionTimeout()) {
args.set_cancel(true);
}
else {
if (sender._postBackSettings.sourceElement.id == '<%= gvResults.ClientID %>') {
//do something because of this
}
}
}
EDITHere is the method of checking for timeout on the client side.
var sessionTimeoutDateTime = new Date();
var sessionTimeoutInterval = <%= this.SesstionTimeoutMinutes %>;
function CheckForSessionTimeout() {
var currentDateTime = new Date()
var iMiliSeconds = (currentDateTime - sessionTimeoutDateTime);
if (iMiliSeconds >= sessionTimeoutInterval) {
ShowSessionTimeout();
return true;
}
return false;
}
I would recommend that you do not have each control execute the same javascript function. OR, if they do, pass a parameter that indicates which one executed it.
Then, you can include your ajax in the js function that the control executes.
And, if I'm not understanding the issue correctly, perhaps you could explain it in more detail or post some code.
I've read some documentation, and turns out you CAN check the "sender" control. JS in the question is updated to show the proper method signature.
This article gives even better explanation.

Resources