Aşağıdaki örnekte, tüm class alanlarını kontrol edeceğiz. Daha fazla bilgi için burayı tıklayın.


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;

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

/**
* @var string
*
* @Serializer\Type("string")
*/
public $password;
}

Validator Constraint


namespace Application\BackendBundle\Validator\Constraint;

use Symfony\Component\Validator\Constraint;

/**
* @Annotation
*/
class UserCreate extends Constraint
{
const INVALID_USERNAME = 'Username must form of only alphabetic and numeric characters.';
const MIN_PASSWORD = 'Password cannot be less than 6 characters.';
const MAX_PASSWORD = 'Password cannot be longer than 20 characters.';
const USERNAME_PASSWORD_MATCH = 'Username and Password cannot be same.';

public function getTargets()
{
return self::CLASS_CONSTRAINT;
}

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

namespace Application\BackendBundle\Validator\Constraint;

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

class CreateUserValidator extends ConstraintValidator
{
public function validate($userCreate, Constraint $constraint)
{
if (! ctype_alnum($userCreate->username)) {
$this->context
->buildViolation($constraint::INVALID_USERNAME)
->atPath('username')
->addViolation();
} else if (mb_strlen(trim($userCreate->password)) < 6) {
$this->context
->buildViolation($constraint::MIN_PASSWORD)
->atPath('password')
->addViolation();
} else if (mb_strlen(trim($userCreate->password)) > 20) {
$this->context
->buildViolation($constraint::MAX_PASSWORD)
->atPath('password')
->addViolation();
} else if ($userCreate->username == $userCreate->password) {
$this->context
->buildViolation($constraint::USERNAME_PASSWORD_MATCH)
->atPath('username_password_match')
->addViolation();
}
}
}