简体   繁体   中英

Validate a form on the fly or skip a rule in Symfony2

I have a entity and validations.yml ... for register a new record in the entity(table) I have a rule for a unique email and works fine but when I try to make a simple login passing the email and password, and when pass for $form->isValid() I don't want to display the message about Email already taken instead I want to skip this rule or a way to just compare the email and password and only compare if the email is empty or password aswell.

Or whether exists a way to add a validation on the fly.

Thank you in advance!

Yes you can "validate on the fly" using the Symfony validator service. It's explained quite clearly in the Symfony validation documentation. Example:

$author = new Author();
// ... do something to the $author object

$validator = $this->get('validator');
$errors = $validator->validate($author);

return (count($errors) > 0) ? new Response('Some Error Message') : new Response('Some Success Message');

You can even tell it which fields you want to validate. If you can post your actual code and what the specific problem is that you are experiencing with it, I can try to provide a more specific answer.

To validate only specific fields in your form inside your controller action:

use Symfony\Component\Validator\Constraints\Email;

...

$emailConstraint = new Email();

// all constraint "options" can be set this way
$emailConstraint->message = 'Invalid email address';

// use the validator to validate the value
$errorList = $this->get('validator')->validateValue(
    $email,
    $emailConstraint
);

if (count($errorList) == 0) {
    // this IS a valid email address, do something
} else {
    // this is *not* a valid email address
    $errorMessage = $errorList[0]->getMessage();

    // ... do something with the error
}

More on validating raw values .

What you want is validation groups. symfony.com/doc/current/book/forms.html#validation-groups

Though personally I just create different form types and apply validators directly to the form elements.

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