1
1
import { FormlyExtension , FieldValidatorFn , FormlyConfig } from '../../services/formly.config' ;
2
2
import { FormlyFieldConfigCache } from '../../components/formly.field.config' ;
3
3
import { AbstractControl , Validators , ValidatorFn } from '@angular/forms' ;
4
- import { isObject , FORMLY_VALIDATORS , defineHiddenProp , isUndefined , isPromise } from '../../utils' ;
4
+ import { isObject , FORMLY_VALIDATORS , defineHiddenProp , isUndefined , isPromise , wrapProperty } from '../../utils' ;
5
5
6
6
/** @experimental */
7
7
export class FieldValidationExtension implements FormlyExtension {
@@ -29,7 +29,7 @@ export class FieldValidationExtension implements FormlyExtension {
29
29
return ;
30
30
}
31
31
32
- const validators : ValidatorFn [ ] = type === 'validators' ? this . getPredefinedFieldValidation ( field ) : [ ] ;
32
+ const validators : ValidatorFn [ ] = type === 'validators' ? [ this . getPredefinedFieldValidation ( field ) ] : [ ] ;
33
33
if ( field [ type ] ) {
34
34
for ( const validatorName in field [ type ] ) {
35
35
if ( validatorName === 'validation' && ! Array . isArray ( field [ type ] . validation ) ) {
@@ -51,14 +51,25 @@ export class FieldValidationExtension implements FormlyExtension {
51
51
) ;
52
52
}
53
53
54
- private getPredefinedFieldValidation ( field : FormlyFieldConfigCache ) : ValidatorFn [ ] {
55
- return FORMLY_VALIDATORS
56
- . filter ( opt => ( field . templateOptions && field . templateOptions . hasOwnProperty ( opt ) ) || ( field . expressionProperties && field . expressionProperties [ `templateOptions.${ opt } ` ] ) )
57
- . map ( ( opt ) => ( control : AbstractControl ) => {
54
+ private getPredefinedFieldValidation ( field : FormlyFieldConfigCache ) : ValidatorFn {
55
+ let VALIDATORS = [ ] ;
56
+ FORMLY_VALIDATORS . forEach ( opt => wrapProperty ( field . templateOptions , opt , ( value , oldValue ) => {
57
+ VALIDATORS = VALIDATORS . filter ( o => o !== opt ) ;
58
+ if ( value != null && value !== false ) {
59
+ VALIDATORS . push ( opt ) ;
60
+ }
61
+ if ( value !== oldValue && field . formControl ) {
62
+ field . formControl . updateValueAndValidity ( { emitEvent : false } ) ;
63
+ }
64
+ } ) ) ;
65
+
66
+ return ( control : AbstractControl ) => {
67
+ if ( VALIDATORS . length === 0 ) {
68
+ return null ;
69
+ }
70
+
71
+ return Validators . compose ( VALIDATORS . map ( opt => ( ) => {
58
72
const value = field . templateOptions [ opt ] ;
59
- if ( value === false ) {
60
- return null ;
61
- }
62
73
switch ( opt ) {
63
74
case 'required' :
64
75
return Validators . required ( control ) ;
@@ -73,7 +84,8 @@ export class FieldValidationExtension implements FormlyExtension {
73
84
case 'max' :
74
85
return Validators . max ( value ) ( control ) ;
75
86
}
76
- } ) ;
87
+ } ) ) ( control ) ;
88
+ } ;
77
89
}
78
90
79
91
private wrapNgValidatorFn ( field : FormlyFieldConfigCache , validator : string | FieldValidatorFn , validatorName ?: string ) {
0 commit comments