Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In example below, we're just going to validate whole class. 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;

/**
* @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();
}
}
}