blog

  • Home
  • blog
  • Validating your data with Respect Validation

Validating your data with Respect Validation

Validation is an important aspect of every application’s interaction with data. Instead of reinventing the wheel every time, the community collaborated on some useful packages like Symfony, Laravel, Zend, etc. In this article, we’re going to introduce a new package called Respect Validation, which provides some nice new features. Let’s get started.

When using a framework, there is a great chance that you have a validation component shipped with it. The Symfony Validator Component provides a set of standard validation rules that you’ll need for your application.

class UserSubscriptionForm
{
    protected $email;

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('email', new \Assert\Email([
            'message' => 'Invalid email.'
        ]));
    }
}

I’m sure your subscription form contains more than just an email, but let’s keep it simple. Inside your controller you’ll have to trigger the validation like so:

public function store(Request $request){
    $userSubscriptionForm = UserSubscriptionForm::fromInput($request->all());
    $validator = $this->get('validator');
    $errors = $validator->validate($userSubscriptionForm);

    if (count($errors) > 0) {
        // redirect with errors
    }

    // return success
}

Continue reading %Validating your data with Respect Validation%

LEAVE A REPLY