refactor(forms): Log a warning when FormGroup keys include a dot. (#50642)

Due to the dotted synthax to resolve controls, keys in FormGroups cannot include dots.

fixes #50608

PR Close #50642
This commit is contained in:
Matthieu Riegler
2023-06-09 18:12:45 +02:00
committed by Dylan Hunn
parent 7981aad30e
commit 43115da986
2 changed files with 26 additions and 1 deletions
+16
View File
@@ -177,6 +177,7 @@ export class FormGroup<TControl extends {[K in keyof TControl]: AbstractControl<
controls: TControl, validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null) {
super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
(typeof ngDevMode === 'undefined' || ngDevMode) && validateFormGroupControls(controls);
this.controls = controls;
this._initObservables();
this._setUpdateStrategy(validatorOrOpts);
@@ -588,6 +589,21 @@ export class FormGroup<TControl extends {[K in keyof TControl]: AbstractControl<
}
}
/**
* Will validate that none of the controls has a key with a dot
* Throws other wise
*/
function validateFormGroupControls<TControl>(
controls: {[K in keyof TControl]: AbstractControl<any, any>;}) {
const invalidKeys = Object.keys(controls).filter(key => key.includes('.'));
if (invalidKeys.length > 0) {
// TODO: make this an error once there are no more uses in G3
console.warn(`FormGroup keys cannot include \`.\`, please replace the keys for: ${
invalidKeys.join(',')}.`);
}
}
interface UntypedFormGroupCtor {
new(controls: {[key: string]: AbstractControl},
validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
+10 -1
View File
@@ -223,7 +223,6 @@ describe('FormGroup', () => {
});
});
describe('touched', () => {
let c: FormControl, g: FormGroup;
@@ -2411,5 +2410,15 @@ describe('FormGroup', () => {
}
});
});
it('should throw with invalid keys', () => {
const consoleWarnSpy = spyOn(console, 'warn');
new FormGroup({
foo: new FormControl('foo'),
bar: new FormControl('foo', [Validators.required]),
'baz.not.ok': new FormControl('baz')
});
expect(consoleWarnSpy).toHaveBeenCalledTimes(1);
});
});
})();