简体   繁体   中英

Symfony2 validation filters

In my Symfony 2 application I need to filter input before passing it on to validation [1], however, I can't seem to find any system within Symfony to do this.

The type of filtering I looking for is eg to be able to filter a dash out of a specific field before validating it. Eg users can enter 123-123 but the only accepted value is 123123 . Just as I can set up validation rules with constraints, I'm looking for something similar for filters.

[1] http://symfony.com/doc/current/book/validation.html

Nifr's answer is good but is missing of an important alternative that, if I understand correctly your question, seems to fit perfectly your needs.

You can use a hook that is pretty much an event listener: if something happens or is going to happen, it intercepts the event and redirect it to your function.

In this case, you need a PRE_BIND hook (is deprecated since 2.3 version, now it's called PRE_SUBMIT )

Read this if you need help about

Either write your own Validation Assert to filter and then proxy the other validators for this purpose ...

... or one or multiple Regex Asserts .

... or use a DataTransformer to transform/filter the input.

With the DataTransformer involved you could aswell consider creating a new FieldType which renders two inputs with a seperator like the date form-field does. ( if not not used with widget => single_text )

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