I am having a problem setting the customvalidator on client side.
based on a particular hidden field value, the onClientClick event of a button should be firing a function which sets the isValid property of a CustomValidator to false.
Below is some code :
Code Behind :
protected void Page_Load(object sender, EventArgs e)
{
if (hiddenfieldValue == true)
{
btnSend.OnClick = "someJavascriptFunction()";
}
}
ASPX File :
function someJavascriptFunction()
{
if (hiddenfieldValue == true)
// Show Validation and dont do postback
vldValdiator.isValid = false;
return false; //Dont do Postback
else
return true; Do Postback
}
<asp:CustomValidator ID="vldValidator" runat="server" Text = "ABC"/>
I am not able to set the isValid property on client side based hidden field values.
Please Help . Thanks in advance.
Method 1
You could try setting the Page_IsValid property to false within the button onClientClick event. This would force the page into it's non validate state as far as the asp.net validators are concerned.
Basic example
function ButtonOnClickClient()
{
if ($('#hiddenFieldID').val() == 'someValue')
{
Page_IsValid = false;
}
}
Honestly - i'm not convinced that the Page_IsValid property won't be reset. You would need to try
Method 2
you could make the customvalidator client validation check the hidden field and make the validator pass or fail validation on that basis. The button onclient click event could then call the Page_ClientValidate() function which will force validation on the page. This will then set the correct validation property.
Basic example 2
function CustomValidatorClientValidate(source, arguments)
{
if ($('#hiddenFieldID').val() == 'someValue'){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
function ButtonOnClientClick()
{
Page_ClientValidate();
}
This uses JQuery - because i find it easier to write an example that way. By no means mandatory to use it. Also I'm assuming the asp.net validator API is present. It should be if you have included those controls but you could always tighten up by adding checks for the function names
ALSO
If you are using validation groups which you probably will be the call will become
Page_ClientValidate(validationGroupName);
Method 3
You could try that about but set the the isvalid property of the customvalidator. That should give you the more direct control of the validator that you want. The reference below says
isvalid Boolean property.This is a property on each client validator
indicating whether it is currently valid
I've done something similar to the first two but I've not personally tried this one.
In general
The general the method you are using is direct manipulation of the javascript API that the asp.net validators use. It's not massively pretty but you can get the control that you want
Reference
This gives a reference to the javascript API you are trying to use. It's a lengthy article but the bit you want is about halfway down
http://msdn.microsoft.com/en-us/library/Aa479045
Good Luck
More
I really need to leave this but your code is wrong here - it's OnClientClick.
btnSend.OnClientClick = "someJavascriptFunction()";
Use This to Bind the Event.
btnSend.Attributes.Add("onclick","return someJavascriptFunction();")
Related
I am trying to use the jQuery validation plugin with tinyMce but I am having a small problem.
By default the validation plugin has the following behavior: initially every field is marked as valid and the validation is lazy i.e. the error isn't shown until the user enters a value and moves away from the field. Once a field is marked as invalid, it is eagerly validated which means the validation is done on every key stroke.
I am having difficulty simulating this behavior for the TinyMCE field. If I use the onChange method the validation is always done on focus out. If I use the onKeyDown method, validation is done on every key stroke, even if the user is changing the field for the first time.
Is there some way I can use a combination of onChange and onKeyDown in order to mimic the default behavior of jQuery validation plugin? Here is the code that I currently have:
function(ed) {
ed.onChange.add(function(ed, e) {
tinyMCE.triggerSave();
jQuery('#'+ed.id).valid();
});
}
In case I am not making sense you can read how the validation plugin behaves here.
Thanks in advance!
I think you're going to have to have a valid state variable
Something like this
function(ed) {
var validState = true;
ed.onKeyDown.add(function(ed, e) {
if (validState) {
return
}
else {
// check if new content is valid
validState = jQuery('#'+ed.id).valid();
}
}
ed.onChange.add(function(ed, e) {
validState = jQuery('#'+ed.id).valid();
if (validState){
tinyMCE.triggerSave();
}
});
}
Note this is just some sample code. I haven't verified that this will work
Is there a way to determine from JavaScript if a page contains a scriptmanager, an updatepanel or if the __doPostBack is called from an update panel or is a partialpostback?
When one update panel is called, then there are two functions that trigger from javascript side. Inside this functions you can also get the Ids of the panel that trigger this update. If there is a full post back outside of an update panel, then you need to capture the submit of the form.
Here are the code that triggered when an update panel is going to upadte, together with the functions that show the update panel ids that make the trigger.
<script>
if(window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
else
{
// no ScriptManager found
}
function InitializeRequest(sender, args)
{
// get the array of update panels id
var UpdPanelsIds = args.get_updatePanelsToUpdate();
// get the Post ID
args.get_postBackElement().id;
}
function EndRequest(sender, args) {
}
</script>
'Dan Davies Brackett' Correct describe how you can know if the ScriptManager exist.
If I understand correctly, there are two questions here:
(1) how do I tell in JavaScript whether a ScriptManager exists on a page?
If the server-side page contains a ScriptManager, there will be a PageRequestManager available on the client. You can discover whether it exists with:
var haveScriptManager = window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager;
(2) how do I tell whether __doPostBack is synchronous?
Once you have a handle to the local PageRequestManager, you can hook the event that fires before every postback and check whether it's synchronous or asynchronous. Again, the documentation for the PageRequestManager will give you all the details of how to do that.
Emit the scriptManager clientID to some clientside javascript, then look for it on the page (document.getElementById(emittedClientID)
You can rename __doPostBack with... __NewDoPostBack = __doPostBack, then create a new function such as...
__doPostBack = function(whatever arguments __NewDoPostBack takes){
alert("We're doing a post back");
__NewDoPostBack(whatever arguments __NewDoPostBack takes)
}
I've got a web page that uses an UpdatePanel and validation within.
Because of requirements specified within, I have to display a custom model when validation fails and so far, I've only been able to do this by overriding the Page_ClientValidate client side function:
function Page_ClientValidate(validationGroup) {
Page_InvalidControlToBeFocused = null;
if (typeof(Page_Validators) == "undefined") {
return true;
}
var i;
for (i = 0; i < Page_Validators.length; i++) {
ValidatorValidate(Page_Validators[i], validationGroup, null);
}
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
Page_BlockSubmit = !Page_IsValid;
if(!Page_IsValid)
{
displayError();
}
return Page_IsValid;
}
This works great, but I've noticed that when using it within an UpdatePanel, as soon as the UpdatePanel generates new content, it seems the ScriptResource.axd's containing the original Page_ClientValidate is downloaded again, thus overriding my override (if that makes any sense).
Now, it displays the errors beside the fields, but doesn't call my displayError function.
Any suggestions?
I've thought about possibly writing something to monitor the error span's to see if they become visible, but not sure if that's overkill at the moment.
Thanks
Gavin
Are you using $(document).ready(...)?
if so, try to use the pageLoad() of the client side
http://encosia.com/document-ready-and-pageload-are-not-the-same/
I want to write a custom valadiator for a dijit.form.ValidationTextBox. Unfortunately, dijit.form.ValidationTextBox.validator is called each type an ontype event occurs. To get around this the documentation suggests :
There is one small catch here: this validator will be called onType, meaning it will be sending requests to the backend on every key stroke. If you do not want that to happen, you may want to add another check in the beginning so that it always returns true if the validation text box is on focus
However, the don't quite mention how to check and see if the textbox has focus.
Any suggestion?
In the documentation you mentioned (found here http://dojotoolkit.org/reference-guide/dijit/form/ValidationTextBox-tricks.html#dijit-form-validationtextbox-tricks) they mention creating a custom validation function. Try adding the following check to the beginning of the function:
dijit.byId("validationTextBoxNodeId").validator = function (value, constraints) {
if(document.activeElement.id == "validationTextBoxNodeId") return true; //don't check while typing
// Check that email has not been used yet.
if (some-checks) {
return true;
} else {
return false;
}
}
Or, if you're not assigning a manual id such as "validationTextBoxNodeId" to the validation text box and are creating everything programmatically (which has, in my experience, been the far more likely scenario):
new dijit.form.ValidationTextBox({
name:"email",
//insert other properties like value, required or invalidMessage here
validator: function() {
if(this.id == document.activeElement.id) return true; //don't check while typing
//real checks go here
if (some-checks) {
return true;
} else {
return false;
}
}
});
Notice you don't need to explicitly refer to the id of the box because the validation function works within its scope. You could probably accomplish the same thing in the first example using dojo.hitch() if you needed to.
Also, note that this only works if your target browser(s) supports document.activeElement ( Which browsers support document.activeElement?).
In .NET 2.0, I have several client side validators ala the .NET validator controls. These run fine when I click a button...until I add my own javascript function to this button. Instead of running in addtion to the validators, it seems to prevent them from running at all.
To be clear, the validator controls are basic required field validators, and here is the javascript I added:
<script language="javascript">
function yaya()
{
var chkAmount = document.frmSearchFor.txtCheckAmount.value;
var amtApplied = document.frmSearchFor.lblAmountApplied.value;
if (amtApplied < chkAmount)
{
return confirm('Continue?');
}
}
</script>
And it's tied to the button like this...
OnClientClick="return yaya();
those are probably not the ID's being rendered to your page. Try this:
function yaya()
{
var checkAmount = parseFloat(document.getElementById("<%=txtCheckAmount.ClientID %>").value);
var amoutApplied = parseFloat(document.getElementById("<%=lblAmountApplied.ClientID %>").text);
if (amoutApplied < checkAmount)
{
return confirm('Continue?');
}
}
And try attaching it like this:
OnClientClick="javascript:yaya();";
Client-side validation is done via javascript just like your client click. When you specify the client-side event, I'm guessing there's nowhere for the validation code to attach. You may need to modify either the validation code to call your function, or your function to call the validation code. Probably the latter is easier. Instead of assigning OnClientClick at design time, add a client script that stores the current click handler function, creates a function that runs your code and then runs the stored handler function, and attaches that new function as the click handler.
<script>
var baseHandler = myElement.onclick;
myElement.onClick = function() {
// run your code here
baseHandler();
}
</script>
issue is that you are specifying a return in your OnClientClick attribute. when the page renders, it comes out like this
<input ... onclick="return yaya();WebForm_DoPostBackWithOptions...
after yaya completes, the onclick function concludes and I believe it's shutting down any further action that would normally happen before the form is submitted. it's kind of ugly but you can get around this by only having a return when your function evaluates to false:
OnClientClick="if (!yaya()) { return false; }"
for this to work you should also include return true; at the end of your function in case the conditions for the if check are not met.
you may also be having issues with references to elements as Hunter mentions but you're not providing your markup to verify that.