@@ -125,6 +125,7 @@ export function validateRules(
125125 value : StoreValue ,
126126 rules : RuleObject [ ] ,
127127 options : ValidateOptions ,
128+ validateFirst ?: boolean ,
128129) {
129130 const name = namePath . join ( '.' ) ;
130131
@@ -179,20 +180,40 @@ export function validateRules(
179180 } ;
180181 } ) ;
181182
182- const summaryPromise : Promise < string [ ] > = Promise . all (
183- filledRules . map ( rule => validateRule ( name , value , rule , options ) ) ,
184- ) . then ( ( errorsList : string [ ] [ ] ) : string [ ] | Promise < string [ ] > => {
185- const errors : string [ ] = [ ] . concat ( ...errorsList ) ;
183+ const rulePromises = filledRules . map ( rule => validateRule ( name , value , rule , options ) ) ;
186184
187- if ( ! errors . length ) {
188- return [ ] ;
189- }
185+ const summaryPromise : Promise < string [ ] > = validateFirst
186+ ? finishOnFirstFailed ( rulePromises )
187+ : finishOnAllFailed ( rulePromises ) . then ( ( errors : string [ ] ) : string [ ] | Promise < string [ ] > => {
188+ if ( ! errors . length ) {
189+ return [ ] ;
190+ }
190191
191- return Promise . reject < string [ ] > ( errors ) ;
192- } ) ;
192+ return Promise . reject < string [ ] > ( errors ) ;
193+ } ) ;
193194
194195 // Internal catch error to avoid console error log.
195196 summaryPromise . catch ( e => e ) ;
196197
197198 return summaryPromise ;
198199}
200+
201+ async function finishOnAllFailed ( rulePromises : Promise < string [ ] > [ ] ) : Promise < string [ ] > {
202+ return Promise . all ( rulePromises ) . then ( ( errorsList : string [ ] [ ] ) : string [ ] | Promise < string [ ] > => {
203+ const errors : string [ ] = [ ] . concat ( ...errorsList ) ;
204+
205+ return errors ;
206+ } ) ;
207+ }
208+
209+ async function finishOnFirstFailed ( rulePromises : Promise < string [ ] > [ ] ) : Promise < string [ ] > {
210+ return new Promise ( resolve => {
211+ rulePromises . forEach ( promise => {
212+ promise . then ( errors => {
213+ if ( errors . length ) {
214+ resolve ( errors ) ;
215+ }
216+ } ) ;
217+ } ) ;
218+ } ) ;
219+ }
0 commit comments