Issue
I'm pretty sure this is easy to do but I can't find the solution anywhere.
I have a formGroup
called agenda. All the fields are required and valid before the submit is enabled. I also want the last field to be only valid if it equals a certain number entered by the user (defined by solution
). I've simplified the code below:
<form (ngSubmit)="submitForm()" [formGroup]="agenda" class="bodytext">
<ion-input type="text" name="email" formControlName="email" required></ion-input>
<ion-input type="text" name="userSolution" formControlName="userSolution" required></ion-input>
<ion-button type="submit" expand="block" [disabled]="agenda.invalid">Submit</ion-button>
</form>
then there's my constructor in the ts file:
constructor( http: HttpClient, private formBuilder: FormBuilder) {
this.http = http;
this.agenda = this.formBuilder.group({
email: [''],
userSolution: [''],
});
}
Solution
I have created a working example on stackblitz where I have assumed the number to be 20 when the condition is true. Also you can use the required validator when you are initializing the form.
I have used a custom validator which returns the error name as key and boolean true as value {errorName: true}
if condition doesn't matches and that error name can be used for validation error message.
export class AppComponent implements OnInit {
agenda: FormGroup;
solution = 20;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.initForm();
}
initForm() {
this.agenda = this.formBuilder.group({
email: ["", Validators.required],
userSolution: ["", [Validators.required, this.myValidator(this.solution)]]
});
}
myValidator(num: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (
control.value !== undefined &&
(isNaN(control.value) || control.value != num)
) {
return { notEqual: true };
}
return null;
};
}
}
Form-
<form [formGroup]="agenda" class="bodytext">
<input type="text" name="email" formControlName="email">
<input type="text" name="userSolution" formControlName="userSolution">
<button type="submit" expand="block" [disabled]="agenda.invalid">Submit</button>
</form>
Demo Link - stackBlitz
Answered By - Sarthak Malik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.