S
S
Sergey Kalenik2015-02-06 14:49:22
JavaScript
Sergey Kalenik, 2015-02-06 14:49:22

Yii2 how to run form validation manually and get result?

Good afternoon.
There was a problem.
I have a wizard, in the wizard one of the steps uses an ActiveForm form.
Before moving on to the next step, I want to run the form validation manually.
If you look at the code from yii.activeForm.js, then in theory this should be done like this:

var $form = $('#profile-form');	
$('#profile-form').yiiActiveForm('validate');

the method is launched, falls off on the internal attribute validation check:
if (data.submitting || this.status === 2 || this.status === 3) {...}

there is an alternative option, manually run the validation of each form field and, based on the validation results, already proceed to the next step of the wizard:
$('#profile-form').yiiActiveForm('validateAttribute', 'profileform-email');

but I don't like that the code comes out a bit unwieldy.
how to run form validation manually?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Kalenik, 2015-02-09
@monax-at

Used yii2, additional library for gui - fuelux
The solution is this.
I hang up a callback for the transition to the next element of the wizard, if it enters the list, then I stop the transition to the next element and start validation:

$('#cart-wizard').on('actionclicked.fu.wizard', function(evt, data) {
  if(data.direction !== 'next') {return;}
  if(data.step === 2) {
    Cart.runValidation();
    return false;
  }			
}

I go through a pre-formed array with the IDs of the fields being validated and manually start the validation through yiiActiveForm.
runValidation: function () {
    Cart.profileValidator.validations = [];
    var form = $(Cart.profileValidator.formSelector);
    for(var key in Cart.profileRows) {
      form.yiiActiveForm('validateAttribute', Cart.profileRows[key]);
    }
  },

Next, I hang a callback on the validation event of each required form field.
When all fields are validated, I check if there are any errors, and if not, I go to the next step of the wizard:
$(Cart.profileValidator.formSelector).on('afterValidateAttribute', function (event, attribute, messages) {
      Cart.profileValidator.validations.push({
        id: attribute.id,
        message: messages[0]
      });
      if (Cart.profileRows.length != Cart.profileValidator.validations.length) {
        return;
      }			
      var hasError = false;
      for(var key in Cart.profileValidator.validations) {
        if (Cart.profileValidator.validations[key].message != undefined ) {
          hasError = true;						
          break;
        }
      }
      if (!hasError) {
        $('#cart-wizard').wizard('selectedItem', {
          step: 3
        });					
      }			
    });

M
Maxim Timofeev, 2015-02-08
@webinar

Here it is necessary to understand your wizard. Does it work through the controller or is it in javascript?
Read about ajax form validation in yii2, for example here: coderlife.eu/php/sozdanie-ajax-validacii-na-primer...

I
IStrangerX, 2015-09-22
@IStrangerX

The question is old, but nevertheless I will publish my solution (using emulation of submitting a form).
The native implementation does not allow you to flexibly control the implementation of form validation on the client - everything is too tailored to submit a single form.

var validationEnabled = false,
    $form             = $('#form_id');

/**
 * Validates form.
 * Note: after first successful validation of form this state of form will be cached (this is yii.activeForm.js-native feature).
 * @param {Function} callback Function as first argument passes result of validation.
 */
function validateForm(callback) {

    if (!validationEnabled) {
        $form.on('submit', function () {
            var $form       = $(this),
                yiiFormData = $form.yiiActiveForm('data');

            callback(yiiFormData.validated);

            return false;                   // we stop submitting of form (we submit only for performing of validation)
        });

        validationEnabled = true;           // don't use of .one(handler), because it can't prevent form submitting
    }


    $form.trigger('submit');    // this runs validation of form
}


// ... do something


validateForm(function (successValidated) {
    if (successValidated) {
        // ... do something
    }
});

* Of course, it is even easier to deceive the widget, such as the form has been sent (but it is more difficult to pick out the validation result there):
$form.yiiActiveForm('data').submitting = true;
$form.yiiActiveForm('validate');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question