简体   繁体   中英

Sonata Admin Bundle - String Validation

I've some forms in my Sonata Admin Bundle and some fields are set as "required = true". Now, you can circumvent this requirement with an empty string, eg with space. It works even for integer-types..

How can I build a validation, which secures from some unallowed entries ?

Thank you

You can add a custom callback validator to verify your strings with all cases you want.

Just add in your admin class:

/**
 * {@inheritdoc}
 */
public function validate(ErrorElement $errorElement, $object)
{
    $errorElement
        ->assertCallback(array('validateMyEntity'))
    ;
}

and in your entity:

use Symfony\Component\Validator\ExecutionContext;

/**
 * Validates my entity and throw violations
 */
public function validateMyEntity(ExecutionContext $context)
{
    $title = $this->getTitle();

    if (empty($title)) {
        $context->addViolation('Title can\'t be empty.');
    }
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM