1
votes

I validated my form by two code parts below:

this.formAdd = this.formBuilder.group({
  objectId: [null, [Validators.required]],
  objectOrder: [null, [Validators.required]],
  objectName: [null, [Validators.required]],
  objectCreateDate: [null, [Validators.required]],
  objectSex: [null, [Validators.required]],
  objectAddress: [null, [Validators.required]],
  objectNational: [null, [Validators.required]],
  objectType: [null, [Validators.required]],
});

and

this.formUpdate = this.formBuilder.group({
  objectId: [[null], [Validators.required]],
  objectOrder: [[null], [Validators.required]],
  objectName: [[null], [Validators.required]],
  objectCreateDate: [[null], [Validators.required]],
  objectSex: [[null], [Validators.required]],
  objectAddress: [[null], [Validators.required]],
  objectNational: [[null], [Validators.required]],
  objectType: [[null], [Validators.required]],
});

The first part is used for validate my form when I add a new record, the second part is used when I update an existed record, when I try to apply the second part of code for add form, it ain't work and the add form always valid even the value is null.

What is the difference between using '[]' and not using '[]'

1

1 Answers

1
votes

This is dependent on the way Angular required validator is built:

it checks for:

  1. the value of control should not be null / undefined
  2. if string / array length should not be 0

So since [null] is a array of length 1 it is considered as valid by angular

You can refer to source code here and here