Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 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 Reply

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...