Validate input field by selection

38 views Asked by At

I have a form with selection sex and 1 input field nationalId, I want to validate ID by sex, like: if user select male, the 12 digit should be odd - and be even for female.

My code:

nationalIdValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      let nationalId = control.get('nationalId')!;
      let sex = control.get('sexId');
      if (!nationalId || !sex || !nationalId.value || !sex.value)
        return null;

      let err = { 'nationalId not valid': { 'id': nationalId?.value, 'sex': sex?.value } }
      return (nationalId[14]?.value == sex?.value) ? err : null;
      // return nationalId ? {forbiddenName: {value: control.value}} : null;
    }
  }
0

There are 0 answers