44
55use JustCoded \FormHandler \Handlers \HandlerInterface ;
66use Valitron \Validator ;
7- use JustCoded \FormHandler \Validator \File as FileValidator ;
7+ use JustCoded \FormHandler \Validator \FileValidator ;
88
99/**
1010 * Class FormHandler
@@ -58,6 +58,9 @@ class FormHandler
5858 public function __construct (array $ validationRules , HandlerInterface $ handler , string $ response = 'json ' )
5959 {
6060 $ this ->rules = $ validationRules ;
61+ if (empty ($ this ->rules ['fields ' ])) {
62+ throw new \Exception ("You should specify 'fields' in validation array. " );
63+ }
6164
6265 $ this ->handler = $ handler ;
6366
@@ -74,19 +77,12 @@ public function __construct(array $validationRules, HandlerInterface $handler, s
7477 public function validate (array $ data )
7578 {
7679 $ this ->formFields = $ data ;
77- $ v = new Validator ($ data );
78-
79- $ v = FileValidator::validate ($ v , $ this ->rules );
80- // create rules from input array.
81- foreach ($ this ->rules ['rules ' ] as $ key => $ params ) {
82- $ rule = $ v ->rule ($ key , $ params ['fields ' ]);
83- if (!empty ($ params ['message ' ])) {
84- $ rule ->message ($ params ['message ' ]);
85- }
86- }
80+ $ v = $ this ->getValidator ($ data );
81+
82+ $ v ->mapFieldsRules ($ this ->rules ['fields ' ]);
8783
8884 // apply labels.
89- if (!empty ($ this ->rules )) {
85+ if (!empty ($ this ->rules [ ' labels ' ] )) {
9086 $ v ->labels ($ this ->rules ['labels ' ]);
9187 }
9288
@@ -100,6 +96,26 @@ public function validate(array $data)
10096 return empty ($ this ->errors );
10197 }
10298
99+ /**
100+ * Create validator object with registered custom validators.
101+ *
102+ * @param array $data Data to validate.
103+ *
104+ * @return Validator
105+ */
106+ public function getValidator ($ data )
107+ {
108+ $ v = new Validator ($ data );
109+
110+ // register additional validators.
111+ FileValidator::register ($ v );
112+
113+ return $ v ;
114+ }
115+
116+ /**
117+ * Sending email by handler
118+ */
103119 public function process ()
104120 {
105121 $ this ->handler ->process ($ this ->formFields );
0 commit comments