eli
eli

Reputation: 205

how to run yii form validation before my js file

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?

Upvotes: 0

Views: 960

Answers (2)

Chinmay Waghmare
Chinmay Waghmare

Reputation: 5456

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
});

Upvotes: 3

Blizz
Blizz

Reputation: 8400

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

Upvotes: 1

Related Questions