简体   繁体   中英

Symfony : Validate email parameter with ParamFetcher

Dears,

I want to validate email directly in the RequestParam. I'm using this kind of REGEX:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

But the parser failed to load the regex in requirements option

The parameter \"&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$\" must be defined.

How could I validate email something like that:

/**
 * @Rest\Patch(
 *     "v1/customer/update",
 *     name="Update a customer"
 * )
 * @RequestParam(
 *     name="email",
 *     requirements="email",
 *     description="The email of the user",
 *     strict=true
 *     )
 */

Thanks in advance

I've got a service to get and convert a parameter to a Value Object, which also validates it as it is being created. I find this allows for a great deal more control than can be given in the RequestParam validations.

# In the same way a string is converted to a Entity, we can convert to a Vo\Username
username_converter:
    class: Ca\Api\Request\ParamConverter\UsernameConverter
    tags:
        - { name: request.param_converter, priority: -2, converter: username_converter }

The UsernameConverter class was quite simple to create as well, following the example and the built-in DoctrineParamConverter , but by putting the value into an object, which is also checked, it was even easier, as there was no database access required.

If the Value Object constructor validation failed, like this (this would be for an email):

if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
    throw new \InvalidArgumentException(sprintf('"%s" is not a valid email', $address));
}

then the exception is caught by the framework.

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