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
Related
When using HTML form validation, having an invalid input value in a form will halt submission of that form. How can I detect that the user attempted a failed form submission? The form's onsubmit handler does not fire when submission is halted by validation failure.
I'm currently listening for keypress and click events on the submit button to detect submit attempts. Is there a better way of detecting a failed form submission?
A simple way to get around this is to add an event listener to each input in the form to see when it has been prevented from submitting. The 'invalid' event should do everything you need.
Example
Array.prototype.slice.call(document.querySelectorAll("[required]")).forEach(function(input){
input.addEventListener('invalid',function(e){
//Your input is invalid!
})
});
More info here
http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/
I suggest you to use noValidate property. You can turn off default validation, and run it manually within onsubmit method
var form = document.getElementById("myForm");
form.noValidate = true; // turn off default validation
form.onsubmit = function(e) {
e.preventDefault(); // preventing default behaviour
this.reportValidity(); // run native validation manually
// runs default behaviour (submitting) in case of validation success
if (this.checkValidity()) return form.submit();
alert('invalid'); // your code goes here
}
you can check it here: https://jsfiddle.net/titulus_desiderio/Laon29f3/
Building on #Titulus' code above, here's how I would do it in jQuery; you can adapt this to native events if need be.
$('form-selector').on('submit', function(event) {
// Don't do anything if constraint validation isn't supported by the browser.
if (
!('checkValidity' in this) ||
// In the unlikely case this is a property but not actually a function.
// Hypothetically, a botched polyfill could do this; it pays to be careful
// and build resilient code.
typeof this.checkValidity !== 'function'
) {
return;
}
if (this.checkValidity() === true) {
// Valid values code.
} else {
// Invalid values code.
// Leave this until the last possible moment in the handler in case there's
// an error in any of the handler code to reduce the chances of a broken
// form where the submit does nothing. If an exception is thrown before
// this, the browser shouldn't get this far, (hopefully) allowing the basic
// form to still work.
event.preventDefault();
}
});
// Tell the browser to not validate automatically, as that would prevent submit
// from being triggered. We prevent the submission above if form doesn't pass
// validation. This is here in case there's an error in the preceding code, so
// this (hopefully) doesn't get applied in that case and browser validation
// takes place as a fallback.
this.noValidate = true;
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();")
I've written a script for my registration form that if there's a keyup event on the username input field, then javascript checks if the username entered is valid and if it's then an ajax function is called to check its availability.
It's working fine. But username can be entered without doing a key up, what to do for those cases? E.g. username can be entered by clicking the input field and selecting a name suggested by the browser, Or by using an auto-form filler. There's no "keyup" in these cases, so what to do for these cases?
And if I am missing some case then pls tell.
Bind the callback to the change event too.
Instead of $('username_input').keyup or $('username_input').bind('keyup', callback) use
$('username_input').bind('keyup change blur', function () {
//
})
[UPDATE]
If you are not using jQuery try
function checkUserName() {
// Ajax validation code
}
userinput = document.getElementById('yourusernameinputid');
userinput.onclick = userinput.onchange = userinput.onblur = checkUserName;
on a side note, you should try learning jQuery. It could save you a lot of time, and help you make better sites in less time.
[UPDATE 2]
It looks like there is no way to detect change via autofill using events. You need to set a timer to automatically check your input at fixed interval and check with you last value.
(function() {
// It is always better to use a closure to prevent the value from
// getting overwritten by another piece of code
var value = '';
setInterval(2000, function() {
if (userinput.value != value) {
checkUserName();
value = userinput.value;
}
});
})();
Test the username when:
The blur event occurs (when the text field loses its focus), and
Before the user sumits the form, or
The change event occurs (I think this is the best).
setInterval is the only way.
Sources:
I want to trigger an event every single time data changes in an HTML text input field regardless of focus
jQuery: What listener do I use to check for browser auto filling the password input field?
I wrote a jquery plugin for validating forms. It bounds itself to the $('element').Submit event to trigger the validation (the bind is inside the plugin). Somehow like this:
// pseudocode
jquery.rdy {
$('form').validate(); //binding the plugin
}
Inside of the validate plug I bind the validation to the submit
//pseudocode
[...]
$().submit(function () {
validating... //returning true/false
if (false) {
return false //prevent submit form
}
}
[...]
So and now my question is how can I bind (in other js scripts for example) other stuff to the submit but just if a validation is done.
so like this
$('form').submit(function () {
if (validate plugin was executed) {
//do stuff like check if validation was returning a true and now do something else
}
}
Hopefully I descriped it right ...my english is not the best but I tryed to be as concrete s possible (and i hope, pseudocode is a right approach as well)
// EDIT: make the problem more concrete:
I'm trying to figure out a way to solve the following problem: (its very out of the context but the problem is exactly there..)
I have a submit event which is doing something depending on some code triggered in a another decleration.
$('element').submit(function () {
if ($(this).hasClass('foo')) {
// do something
}
});
$('element').submit(function () {
$(this).addClass('foo');
});
And now the first function is doing nothing cause it has been triggered before the second one. Is there a clean way to solve this. Maybe I need a timeout event (even I hate them)?
If you are using jQuery.Validate (which it looks like you are with the .validate() syntax), you can just call the isValid() method:
if (validate plugin was executed) {
can then be
if ($('form').isValid()) {
You can bind more functions to the form element with custom names.
$('form').bind('after_validation',function(){ console.log('hello'); });
And trigger them in your submit form function when you need it:
$('form').trigger('after_validation');
http://api.jquery.com/trigger/
Update:
You cannot change the order of your bound submit events without removing them .unbind('submit') and re-applying in the correct order. What you can do is use custom binds (see above) and trigger them exactly when you need it - like.. inside the submit function.
$('form').submit(function () {
//run validation
$('form').trigger('validation');
//did it pass validation?
if($(this).data('invalid')){
console.log('did not pass validation');
return false;
}
//passed validation - submit the form
return true;
});
//add validation to the "form"
$('form').bind('validation',function () {
//do validation on form...
if(false){
$(this).data('invalid',true);
}
});
//add another validator to the form, etc.
$('form').bind('validation',func...
Im using .data() to store variables to the 'form' element so you can access them down the chain.
This is the basis of what you need and can be applied to a custom jquery plugin to form custom named functions. eg. $().validator().
http://docs.jquery.com/Plugins/Authoring
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?).