Require one from two fields using Angular 2

后端 未结 4 1754
感情败类
感情败类 2020-12-29 09:02

I\'m trying to create a contact form. The form looks like this:

4条回答
  •  遥遥无期
    2020-12-29 09:54

    Yes, a custom validator is the way to go.

    Make your form group like this:

    this.contact = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      phone: ['', Validators.required],
      message: ['', Validators.required]
    }, {validator: this.customValidationFunction})
    

    Then have the customValidationFunction check for validation. Made up validation just for example:

    customValidationFunction(formGroup): any {
       let nameField = formGroup.controls['name'].value; //access any of your form fields like this
       return (nameField.length < 5) ? { nameLengthFive: true } : null;
    }
    

    Change each input like this (changing your p tags to divs. Substitute the control name for each and change syntax for the hidden span tag validation where appropriate):

    Enter your name

提交回复
热议问题