how to run yii form validation before my js file

988 views Asked by At

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?

2

There are 2 answers

2
Chinmay Waghmare On BEST ANSWER

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
});
0
Blizz On

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.
}