Skip to content

Latest commit

 

History

History
executable file
·
115 lines (102 loc) · 2.36 KB

File metadata and controls

executable file
·
115 lines (102 loc) · 2.36 KB

3.5 The Callback constraint

3.5.1 Callback by a method name

For the next cases:

namespace Acme\DemoBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\Callback("checkEmail")
 * or
 * @Assert\Callback({"checkEmail"})
 */
class User
{
    // ...

    public function checkEmail()
    {
        if (...) {
            $context->addViolationAt('email', 'Email is not valid');
        }
    }
}

or

/**
 * @Assert\Callback
 */
public function checkEmail()
{
    if (...) {
        $context->addViolationAt('email', 'Email is not valid');
    }
}

You have to create the next callback (pay attention that here you should pass the sourceId parameter):

$('form#user').jsFormValidator({
    callbacks: {
        'checkEmail': function() {
            var errors = [];
            if (...) {
                errors.push('Email is not valid');
            }
            $('#form_email').jsFormValidator('showErrors', {
                errors: errors,
                sourceId: 'check-email-callback'
            });
        }
    }
});

Pure Javascript:

var field = document.getElementById('user');
FpJsFormValidator.customize(field, {
    callbacks: {
        'checkEmail': function() {
            var errors = [];
            if (...) {
                errors.push('Email is not valid');
            }
            var email = document.getElementById('user_email');
            FpJsFormValidator.customize(email, 'showErrors', {
                errors: errors,
                sourceId: 'check-email-callback'
            });
        }
    }
});

3.5.2 Callback by class and method names

In case if you have defined a callback like this:

namespace Acme\DemoBundle\Entity;

/**
 * @Assert\Callback({"Acme\DemoBundle\Validator\ExternalValidator", "checkEmail"})
 */
class User
{
    // ...
}

then you can define it on the JS side like:

// ...
    callbacks: {
        'Acme\\DemoBundle\\Validator\\ExternalValidator': {
            'checkEmail': function () {
                // ...
            }
        }
}

or you can also define it without nesting (like in the 3.5.1 paragraph), but only if the method name is unique:

// ...
    callbacks: {
        'checkEmail': function () {
            // ...
        }
    }