at least one field is required in angular 4 forms

北城余情 提交于 2019-12-03 17:19:05

Disable your button until required fields are not fileld by user

<button type='submit' [disabled]='!contactForm.valid'> Submit</button>

Then call function to check disable like this

<button type='submit' [disabled]='checkValid()'> Submit</button>
checkValid() {
  if(this.contactForm.get('first_name').valid || this.contactForm.get('last_name').valid || this.contactForm.get('email').valid) {
    return false;
  } else {
    return true;
  }
}
private atLeastOneValidator = () => {
    return (controlGroup) => {
        let controls = controlGroup.controls;
        if ( controls ) {
            let theOne = Object.keys(controls).find(key=> controls[key].value!=='');
            if ( !theOne ) {
                return {
                    atLeastOneRequired : {
                        text : 'At least one should be selected'
                    }
                }
            }
        }
        return null;
    };
};

Above is a reusable validator and you can use it like this :

 this.contactForm.setValidators(this.atLeastOneValidator())

This makes the whole contactForm invalid if none of the fields have a value.

Note that the contactForm's default validation will still work nicely and you don't have to care about the number of fields in your form and everything is dynamically handled

EDIT :

Note that the atLeastOneValidator is checking for the values to not to be empty , but if you wanted to say :

At least one of them fields must be valid, then you can simply adjust the conditions to below

 let theOne = Object.keys(controls).find(key=> controls[key].valid );

You can then use the error in your template like this :

 <small *ngIf="contactForm.hasError('atLeastOneRequired')" class="mat-text-warn data_light">{{contactForm.getError('atLeastOneRequired')}}
        </small>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!