Skip to content

Latest commit

 

History

History
executable file
·
66 lines (55 loc) · 2.07 KB

File metadata and controls

executable file
·
66 lines (55 loc) · 2.07 KB

3.7 Custom constraints

If you have your own constraint, you have to implement it on the JS side too. Just add a JS class with a name, similar to the full class name of the related constraint (but without slashes). For example, you have created the next constraint:

// src/Acme/DemoBundle/Validator/Constraints/ContainsAlphanumeric.php
namespace Acme\DemoBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class ContainsAlphanumeric extends Constraint
{
    public $message = 'The string "%string%" contains an illegal character: it can only contain letters or numbers.';
}

// src/Acme/DemoBundle/Validator/Constraints/ContainsAlphanumericValidator.php
namespace Acme\DemoBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ContainsAlphanumericValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!preg_match('/^[a-zA-Za0-9]+$/', $value, $matches)) {
            $this->context->addViolation($constraint->message, array('%string%' => $value));
        }
    }
}

To cover it on JS side, you have to create:

<script type="text/javascript">
    function AcmeDemoBundleValidatorConstraintsContainsAlphanumeric() {
        /**
         * This value will be filled with the real message received from your php constraint
         */
        this.message = '';

        /**
         * This method is required
         * Should return an error message or an array of messages
         */
        this.validate = function(value) {
            if (value.length && !/^[a-zA-Za0-9]+$/.test(value)) {
                return this.message.replace('%string%', value);
            } else {
                return [];
            }
        }

        /**
         * Optional method
         */
        this.onCreate = function() {
            // You can put here some extra actions which will be called after build of this constraint
            // E.g. you can make some preparing actions with the properties
        }
    }
<script/>