angular v 4.4.3.
In Reactive Form, we can write Validators.required
with each form field as below
this.loginForm = this.fb.group({
firstName: ['', [Validators.required, Validators.maxLength(55)]],
lastName: ['', Validators.required],
age: [1, Validators.required],
email: ['', Validators.required],
username: ['', Validators.required],
gender: ['', Validators.required],
address: this.fb.group({
city: ['', Validators.required],
country: ['', Validators.required]
})
});
Here we need to write Validators.required
on each form field.
So I am looking for any solution/method of angular FormBuilder/FormControl which set all field required and can set addition validator on the field if needed.
You can create a customValidator for the whole form,
this.form = this.fb.group({
firstName: ['', [Validators.maxLength(55)]],
....
},
{
validator: this.myValidator()
});
myValidator()
{
return (group: FormGroup) => {
let errors:any={};
let conError:boolean=false;
if (!group.value.firstName)
{
errors.requiredFirstName=true;
conError=true;
}
....
return conError? errors:null
}
}
//The .html becomes like
<form [formGroup]="form " (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="firstName">UserName</label>
<input type="text" class="form-control"
id="firstName" formControlName = "firstName">
<!--see that we ask about form?.errors?requiredFirsName
requiredFirsName is the property we add to errors
we add the condition is touched too
because else, at first, Angular show the error-->
<span class="help-block" *ngIf="form?.errors?.requiredFirstName &&
form.get('firstName').touched ">First Name required</span>
</div>
....
<!--just for check -->
{{form?.errors |json}}
</form>