how to run yii form validation before my js file - javascript

I added some js and css files using assets to my app.
My problem is that I want to run some function when the user click the submit button, but only after yii validator checked if theres no errors.
Right now my function running before yii validator.
How can I do that?

You can use afterValidateAttribute. Try following:
$position = View::POS_END;
$validatejs = <<< JS
$('#formID').on('afterValidateAttribute', function(event, attribute, messages) {
if(messages.length == 0){
// No errors ...
}
});
JS;
$this->registerJs($validatejs, $position);
Updated:
$('#formID').on('beforeValidate', function (event, messages, deferreds) {
// called when the validation is triggered by submitting the form
// return false if you want to cancel the validation for the whole form
}).on('beforeValidateAttribute', function (event, attribute, messages, deferreds) {
// before validating an attribute
// return false if you want to cancel the validation for the attribute
}).on('afterValidateAttribute', function (event, attribute, messages) {
// ...
}).on('afterValidate', function (event, messages) {
// ...
}).on('beforeSubmit', function () {
// after all validations have passed
// you can do ajax form submission here
// return false if you want to stop form submission
});

The beforeSubmit event is triggered after all validation and right before the submit:
$('#formid').on('beforeSubmit', function(e) {
// Do your things
if (cannotSubmitBecauseOfProblem)
e.result = false; // Prevent form submission.
}

Related

jquery function if statement

I'm using jquery validation plugin to validate my form. The function below, displays errors under each field where the error is detected.
errorPlacement : function(error, element) {
error.insertAfter(element.parent());
}
});
How can I evaluate if this function has been used "error has been displayed on screen" or not?
What I'm trying to is to evaluate if form has been validated or not, so I can perform other logic such as disabling submit button or changing button text to "please wait for example".
I'm not sure how I can go about doing that.
Any help would be appreciated.
Thank you
Why don't you just set a boolean variable indicating that the method has been called:
hasError: false,
errorPlacement : function(error, element) {
error.insertAfter(element.parent());
this.hasError = true
}
Then you can check the hasError whenever you need to. Be sure to store hasError on an object in order not to pollute the global namespace.
You could use submitHandler, as it is a callback for handling the actual submit when the form is valid. So ,
$("#your-form").validate({
.....
submitHandler: function(){
//form is valid
//do some logic
$('#your_submit_btn_id').attr('disabled','disabled');
},
.....
});
You can always handle submit event using this code:
$("#myform").validate({
submitHandler: function(form) {
// some other code
// maybe disabling submit button // $('#submit').attr('disabled', true);
// then:
$(form).submit();
}
});
submitHandler will only get called once form gets validated & there is no error.
Documentation can be found here: http://jqueryvalidation.org/documentation/
You can take a look on this:
http://jqueryvalidation.org/validate/
http://www.kianworknotes.com/2013/06/error-handling-in-jquery-validation.html
DEMO
/*error and element is parameter*/
errorPlacement: function(error, element) {
error.appendTo( element.parent("td").next("td") );
}
$('#myform').on('submit', function(){
if($(this).valid()) //this returns true if the form is valid, and false if there is some validation error
{
//submit the form
}
else
{
//disable the submit button or change text as desired
return false; //to avoid form submission
}
});

How can we check postback occur before postback to server by javascript

I Want to Show Loading Image during post back.
When submit event occur it's OK but i want to show for all post back
event.
Problem is I need to check post back occur or not before post back
to server.
jQuery
$("#form1").live("submit", function () {
$('#dvLoading').fadeIn(2000);
});
$("#form1").live("click", function () {
if( **// here I need to check postback occur or not before postback**) {
$('#dvLoading').fadeIn(2000);
}
});
$(document).ready(function () {
$('#dvLoading').hide();
});
HTML
<div id="dvLoading">
<img src="Styles/images/Processing.jpg" />
</div>
From what I understand, you want to check if the postback has already occurred in your 'click' handler. You could do this by defining a variable to check if the postback has already occurred.
var postbackCalled = false;
$("#form1").live("submit", function () {
$('#dvLoading').fadeIn(2000);
postbackCalled = true;
});
$("#form1").live("click", function () {
if(!postbackCalled) {
$('#dvLoading').fadeIn(2000);
}
});

Jquery validation plugin | resetForm is not working

I am trying to clear all error messages as well error highlighting when user click on the clear form button, below are actual requirements
Validate form using Jquery validation
When user click on a field error message should be cleared (per field)
On clicking reset button, every error should be cleared
here is my code
$( document ).ready(function(){
var validator = $("#register_form").validate({
validator.resetForm();
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
For me, first 2 things are working, but when I am trying to clear complete form, I am not able to do this.this is how I am trying to clear it
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
}
But nothing is happening , though with $("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
Quote OP:
1) Validate form using Jquery validation
You cannot put the validator.resetForm(); method inside of the .validate() method.
.validate() is a plugin method where the only thing that can go inside is a comma separated map of the allowed options, {option:value, option:value, etc.}, as per the .validate() method documentation.
resetForm() method documentation
$("#register_form").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
cell: {
required: true
}
},
messages: {
// custom messages
}
});
.validate() method DEMO: http://jsfiddle.net/P46gL/
Quote OP:
2) When user click on a field error message should be cleared (per field)
This is thanks to the focusCleanup option. As you've already done, set it to true and when you click on the field with an error, the error clears.
$("#register_form").validate({
focusCleanup: true,
rules: {
....
focusCleanup DEMO: http://jsfiddle.net/P46gL/1/
Quote OP:
3) On clicking reset button, every error should be cleared
You would call the resetForm() method from within a click handler of the reset button. This will immediately remove all error messages from the entire form and reset the validation plugin to its initial state.
$('#clearform').on('click', function () {
$("#register_form").validate().resetForm(); // clear out the validation errors
});
Make sure the reset button is type="button" or type="reset" or it will trigger validation.
<input type="reset" id="clearform" value="reset form" />
Clear Errors DEMO: http://jsfiddle.net/P46gL/3/
Clearing out the field data
You can clear out the values of the fields by calling a JavaScript .reset() like this.
$('#clearform').on('click', function () {
var form = $("#register_form");
form.validate().resetForm(); // clear out the validation errors
form[0].reset(); // clear out the form data
});
Full Working DEMO: http://jsfiddle.net/P46gL/4/
$("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
to do this you can put one more line below it:
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
$('.error').hide();
}
Although you should do this way:
$( document ).ready(function(){
var validator = $("#register_form").validate({
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
$('[type="reset"]').on('click', function(){
validator.resetForm();
});
});
You should put your validator.resetForm(); in the click event of reset button.
If nothing works then try this approach (specially for clearing data purpose):
1- Form html:
<input type='reset' class="button_grey resetForm" value='Reset'>
2- Jquery validate
// you can add error fields
var validator = $("#clearform").validate({
focusCleanup: true
});
3- Reset the form
$('[type="reset"]').on('click', function(){
$("#clearform").closest('form').find("input[type=text], textarea").val("");
$('input:checkbox').removeAttr('checked');
validator.resetForm();
return false;
});
All error messages will be cleared
$('.btn-reset').on('click', function () {
$( "label.error" ).remove();
});

How to make $.get call during form submission?

I don't want to submit my form with AJAX, but I want to make a progress bar by making a couple of GET requests to the server during form submission, since the submission might take a while with multiple file uploads. I've found that in webkit browsers, I can't make GET requests while the form is submitting and I was seeing that submitting the form to an iframe would allow me to do it.
The markup looks like this:
<form action="/my-action" target="target-iframe">
...
</form>
<iframe name="target-iframe"></iframe>
And the JavaScript:
$(document).ready(function() {
$("form").on("submit", function() {
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
I'm still not getting data back on the GET request--how can I get this to work?
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault(); //stop the form from submitting
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
EDIT
Set a flag that won't allow the form to submit until you've received your response form your get request. Once you've received your response, set your flag to allow your form to submit and then resubmit it programmatically.
$(document).ready(function() {
var canISubmit = false;
$("form").on("submit", function(e) { //add a parameter e - the event object
var el = $(this);
if(!canISubmit) {
e.preventDefault();
$.get("/other-action", function(data) {
canISubmit = true;
el.submit();
});
}
});
});
The only way to be certain that your $.get request was completed is to make sure that the form doesn't submit and redirect the page until your $.get request completes.
EDIT #2
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault();
$.post("url",$(this).serialize())
.done(function(response,status,jqXHR) {
$.get("/other-action")
.done(function(response,status,jqXHR) {
//other stuff done
//refresh the page or do whatever....
})
.fail(function() {
//$.get failed
});
})
.fail(function() {
//$.post failed
});
});
});

How to destroy jQuery validation and any further attempts at submission?

I have the following code for the jQuery validation plugin.... basically on submit, I slide everything up & fade it out... the only problem is, if you're quick enough, you can submit the form multiple times. How can I make sure that any presses of the enter key on the input (or clicks on that submit button) will not submit further?
Basically what happens, is that the form will load up the url in the action attribute when no javascript is there, so purely unbinding doesn't work... (even if it did, I can always press enter / click fast enough to get it to do a couple more....)
jQuery('.desired').validate({
debug: true,
rules: {
email: {
required: true,
email: true
}
},
wrapper: "div",
messages: {
email: "Please enter a valid email address."
},
errorPlacement: function(error, element) {
error.hide().appendTo(element.parent()).hide().slideDown();
},
errorClass: 'help-text',
submitHandler: function(form) {
var $ = jQuery;
var url = $(form).attr('action');
var query = $(form).serialize();
$.ajax({
url: url,
type: "POST",
data: query,
success: function() {
$("<p class='help-jquery'><b>Thanks</b>")
.insertAfter(jQuery(form))
.css('height', function(i,h) {
$(this).hide()
return h;
});
// $(form).css('height', $(form).height());
$(form).slideUp('slow');
$(form).fadeOut({ queue: false, duration: 'slow' });
// $('.help-jquery').fadeIn('slow');
$('.help-jquery')
.css('opacity', 0)
.slideDown('fast')
.animate(
{ opacity: 1 },
{ queue: false, duration: 'slow' }
);
//$('.desired submit').click(function(){
//return false;
//});
},
error: function() {
console.log('Error: did not submit properly');
},
complete: function(e) {
//$('.desired').unbind('submit');
//e.preventDefault();
//return false;
}
});
},
success: function(error,element){
},
highlight: function(error){
// This empty function needs to be here for this to work
}
});
You're on the right track with unbind(), it solves half of your problem because it will effectively suppress validation on form submission.
To solve the second half, you only have to neuter the form's submit event after unbinding, by registering the appropriate handler:
$(form).unbind("submit").submit(function() {
return false;
});
Use a boolean variable, like this:
var didValidate = false;
if(!didValidate) {
jQuery('.desired').validate({
//... your code here
});
}
In your AJAX success function, set didValidate to true.
Have a variable that is 1 or 0. before you do any validation, check that the variable is equal to 0. If it isn't 0, do nothing. If it is, continue. Once the validation passes, set the variable to 1 so that the validation cannot occur again.
Use event namespaces:
The name following the '.' let's you target handlers more specifically.
This at the top of the submit handler:
$(form).bind('submit.temp_submit_hold', function(e){
e.preventDefault();
e.stopPropagation(); //added this in case the plugin's handler func uses bubbling
return false;
} );
This at the top of the complete callback for the ajax call:
$('.desired').unbind('submit.temp_submit_hold');
A little more explanation after seeing your comments in complete. The time to preventDefault is immediately after your onsubmit handler starts working. On complete is when you want to enable it again. So we bind a func that stops it with prevent default and then unbind it to toggle behavior. I also added stopPropagation in case the plugin uses delegation/bubbling.
Probably the simplest is to add something like this to your submithandler
submitHandler: function(form) {
var $ = jQuery;
if ( $.data(form, "submit") ) > "" return false;
$.data(form, "submit", "in progress");
// .. the rest of your handler
}
If you want to allow the form to submitted again later, remove the .data() on success.
Use the .destroy() method.
This question and its answers are quite old. So since that time, the developer has added a .destroy() method to detach the validation plugin from the form.
Destroys this instance of validator freeing up resources and unregistering events.
// Initialize the validation plugin on your form
var validator = $("#myform").validate();
// Remove validation from your form
validator.destroy();
// After this point `#myform` is back to its original state without validation.
https://jqueryvalidation.org/Validator.destroy/
To stop multiple submissions, disable the submit button within the plugin's submitHandler function. (The submitHandler only fires when the form is valid and you've already clicked the submit button.)
submitHandler: function(form) {
// validation & submit success, so disable submit button
$("#yourSubmitButton").prop('disabled', true);
// your ajax code here
return false;
}

Categories