简体   繁体   English

Angular 6 只需要许多字段中的一个字段 Reactive Form

[英]Angular 6 Required only one field from many fields Reactive Form

I am new in angular.我是新来的。 I have one scenario where I need only one field required from 5 fields in the form, means if the user fills at least one field then form makes valid.我有一种情况,我只需要表单中 5 个字段中的一个必填字段,这意味着如果用户至少填写一个字段,则表单有效。

Thanks in advance.提前致谢。

Since you need to check for the validity of whole form only if one of the fields is non empty, You can manually set the validity like below:由于仅当其中一个字段为非空时才需要检查整个表单的有效性,因此您可以手动设置有效性,如下所示:

if(!this.valid){
    this.form.setErrors({ 'invalid': true});
}else{
    this.form.setErrors(null);
}

Where this.valid is your condition based on which you can set the validity this.valid是您可以根据其设置有效性的条件

You can check the example: https://angular-exmphk.stackblitz.io您可以查看示例: https ://angular-exmphk.stackblitz.io

You can also check the answer: FormGroup validation in "exclusive or" which does form validation based on some condition您还可以查看答案: FormGroup validation in "exclusive or" which does form validation based on some condition

Hope this helps希望这可以帮助

See Custom Validators and Cross-field validation in https://angular.io/guide/form-validation请参阅https://angular.io/guide/form-validation中的自定义验证器和跨域验证

Exact example from our app, where at least one phone number field must be entered.来自我们应用程序的确切示例,其中至少必须输入一个电话号码字段。 This is a Validator Function, ie implements https://angular.io/api/forms/ValidatorFn这是一个验证函数,即实现https://angular.io/api/forms/ValidatorFn

import { AbstractControl } from "@angular/forms";
import { Member } from "../../members/member";

export function phone(control: AbstractControl): {[key: string]: any} {
  if (!control.parent) return;
  const form = control.parent;
  const member: Member = form.value;
  if (member.contactphone || member.mobile || member.contactphonesecond) {
    [
      form.controls['contactphone'],
      form.controls['mobile'],
      form.controls['contactphonesecond']
    ].forEach(control => {
      control.setErrors(null);
    });
  } else return {'noPhone': 'None of contact phones is specified'};
}

Member is our class that defines all the form fields, your code will be different but the example of the custom validator should help.成员是我们定义所有表单字段的类,您的代码会有所不同,但自定义验证器的示例应该有所帮助。

Check this example of phone number validator检查此电话号码验证器示例

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NumberValidator } from '../validators/form-validators';


constructor(
    private fb: FormBuilder){}

FormName: FormGroup = this.fb.group({
    phoneNumber: ['', NumberValidator]    
  });

in form-validator file在表单验证器文件中

import { AbstractControl, ValidatorFn } from '@angular/forms';

export const NumberValidator = (): ValidatorFn => {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const mobileRegex = /^[()-\d\s]*$/g;
    const result = mobileRegex.test(control.value);
    return result ? null : { mobileInvalid: { value: control.value } };
  };
};

let me know if you have any doubts.如果您有任何疑问,请告诉我。

    <form [formGroup]="formdata">
<div class="form-group">
    <label for="fieldlabel1">fieldLabel1</label>
    <input type="text" id="fieldlabel1" formControlName="fieldName1" class="form-control"><br>
    <label for="fieldlabel2">fieldLabel2</label>
    <input type="text" id="fieldlabel2" formControlName="fieldName2" class="form-control">
</div>
 </form>

<div class="row">
      <div class="col-sm-12">
        <button type="submit" value="submit" (click)="somefunctioncall()" [disabled]="formdata.invalid">
          Submit
        </button>
      </div>
</div>



import { FormGroup, FormControl, Validators } from '@angular/forms';
import { OnInit } from '@angular/core';

export class test {

formdata: FormGroup;

 ngOnInit() {


  this.formdata = new FormGroup({

      fieldName1: new FormControl("", Validators.compose([
        Validators.required
      ])),
      fieldName2: new FormControl("", Validators.compose([
        // remove required validation for one you dont need.
      ]))
    })   
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM