问题
Using Zend Framework 2. In my application, to edit the data in the database is possible compile an html form or send an http post request(my server is implemented as a web service). In this second case the form is not rendered. Problem: If I put the validations rules in the form when the server recive a post request sent not from the form but from a generic http post request (like an mobile app) the data is not validated/filtered becouse the validations are bind in the form.
Is possible to have an unique centralized validator system ? In my opinion the data must be validate before saving in the db, not in the form!
Ideas?
回答1:
You can find a similar example in the documentation Forms and Actions
In Zend Framework 2 this is done using an input filter, which can either be standalone or defined within any class that implements the InputFilterAwareInterface interface.
So, in this example model entity implements the InputFilterAwareInterface and there are methods setInputFilter and getInputFilter. So later you can call isValid().
I personally put all my filters into src/ModuleName/Filter/ (UserFilter.php). Where implements InputFilterAwareInterface and define getInputFilter() method with all dirty things.
Than in controller, or any other class, just call:
use ModuleName\Filter\UserFilter;
...
$filter = new UserFilter();
$data = $this->params()->fromPost();
if(!$filter->getInputFilter()->setData($data)->isValid()){
$data = $filter->getInputFilter()->getValues();
$errors = $filter->getInputFilter()->getMessages();
// Throw an exception
}
来源:https://stackoverflow.com/questions/24570170/zend-framework-validate-data-in-model-instead-in-the-form