jimbeeer
jimbeeer

Reputation: 1695

Angular Ionic - Validating a form only if a certain field is a certain value

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: [''],
    });
  }

Upvotes: 0

Views: 1633

Answers (2)

Sarthak Malik
Sarthak Malik

Reputation: 125

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

Upvotes: 1

user796446
user796446

Reputation:

To clarify this is particular to Angular and not to Ionic.

You need to compose a validator. Easiest way is to define a function and pass it in.

Without knowing the specifics of your validation requirements, the below pseudo code should help get you there.

NOTE: signature of validateUserSolution will probably change based on your requirements.

 constructor( http: HttpClient, private formBuilder: FormBuilder) 
 {
  this.http = http;
  this.agenda = this.formBuilder.group({
   email: [''],
   userSolution: ['', Validators.compose(validateUserSolution(this.someValue, this.someOtherValue))],
  });
 }

 validateUserSolution(myInput1: string, myInput2: string): boolean {
 // some logic
 }

Upvotes: 0

Related Questions