Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

validation - How to enforce that one date is bigger than the other in angular reactive form?

I've the following reactive form:

  newTripForm = this.formBuilder.group({
    name: new FormControl('', Validators.compose([Validators.required, Validators.minLength(3)])),
    startDate: new FormControl('', Validators.required),
    endDate: new FormControl(''),
  });

How can I add a validator enforcing that the endDate is bigger than the startDate? Also, is there a way to check that the startDate and endDate are dates? I didn't found any validator?

Thank you very much(and sorry for the noob question)

question from:https://stackoverflow.com/questions/65869611/how-to-enforce-that-one-date-is-bigger-than-the-other-in-angular-reactive-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The validators you have used so far are FormControl-validators. They validate a single FormControl. You can also write yourself a validator that validates a FormArray or a FormGroup. A validator would look something like this:

dateOrderValidator(formGroup: FormGroup): ValidationErrors | null {
  const startDate = formGroup.controls['startDate']?.value;
  const endDate = formGroup.controls['endDate']?.value;
  // validate date-strings
  // catch missing values
  if (Date.parse(startDate).getTime() >= Date.parse(endDate).getTime)) {
    // return an appropriate error
  }
}

FormBuilder

FormBuilder's main purpose is to save us some boilerplate. Instead of name: new FormControl(...) we can just write

name: ['initialValue', [<synchronous validators>], [<asynchronous validators]]

or even less (if we have no validators):

name: 'initialValue'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...