In example below, we're just going to validate username property. For more info click here.


Model class


namespace Application\BackendBundle\Model\User;

use JMS\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
use Application\BackendBundle\Validator\Constraint as BackendAssert;

class Create
{
/**
* @var string
*
* @BackendAssert\Username
*
* @Serializer\Type("string")
*/
public $username;

/**
* @var string
*
* @Assert\NotBlank(message="Password is required")
*
* @Serializer\Type("string")
*/
public $password;
}

Validator Constraint


namespace Application\BackendBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class Username extends Constraint
{
const INVALID_CONTENT = 'Username must form of only alphabetic and numeric characters.';
const MIN_LENGTH = 'Username cannot be less than 6 characters.';
const MAX_LENGTH = 'Username cannot be longer than 20 characters.';

public function validatedBy()
{
return get_class($this).'Validator';
}
}

namespace Application\BackendBundle\Validator\Constraint;

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

class UsernameValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (! ctype_alnum($value)) {
$this->context
->buildViolation($constraint::INVALID_CONTENT)
->addViolation();
} else if (mb_strlen($value) < 6) {
$this->context
->buildViolation($constraint::MIN_LENGTH)
->addViolation();
} else if (mb_strlen($value) > 20) {
$this->context
->buildViolation($constraint::MAX_LENGTH)
->addViolation();
}
}
}