@angular/forms#AsyncValidatorFn TypeScript Examples

The following examples show how to use @angular/forms#AsyncValidatorFn. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: account-exists.validator.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
export function accountExists(accountingService: AccountingService): AsyncValidatorFn {
  return (control: AbstractControl): Observable<any> => {
    if (!control.dirty || isEmptyInputValue(control.value)) {
      return of(null);
    }

    if (isString(control.value) && control.value.trim().length === 0) {
      return invalid;
    }

    return accountingService.findAccount(control.value, true).pipe(
      map(account => null),
      catchError(() => invalid),
    );
  };
}
Example #2
Source File: advanced.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Create a generic FormControl
     * @param value value of the FormControl
     * @param validators optional validators to be added to the returned FormControl
     * @param asyncValidators optional asyncValidators to be added to the returned FormControl
     */
    protected createControl(
        value: AdvancedValue | ValueItem | ValueItem[],
        validators?: ValidatorFn[],
        asyncValidators?: AsyncValidatorFn[]
    ): FormControl {
        return new FormControl(
            {
                value,
                disabled: false,
            },
            {
                validators: !!validators ? validators : [],
                asyncValidators: !!asyncValidators ? asyncValidators : [],
                updateOn: "change",
            }
        );
    }
Example #3
Source File: advanced.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Return a standard FormControl compatible with a checkbox component
     * @param field
     * @param validators optional validators to be added to the returned FormControl
     * @param asyncValidators optional asyncValidators to be added to the returned FormControl
     * @param query Query where to fetch advanced values, if omitted, use searchService.query
     */
    public createCheckboxControl(
        field: string,
        validators?: ValidatorFn[],
        asyncValidators?: AsyncValidatorFn[],
        query = this.searchService.query
    ): FormControl {
        const value = this.getBooleanValue(field, query);
        return this.createControl(value, validators, asyncValidators);
    }
Example #4
Source File: advanced.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Return a standard FormControl compatible with a multi-value text input component
     * @param field
     * @param validators optional validators to be added to the returned FormControl
     * @param asyncValidators optional asyncValidators to be added to the returned FormControl
     * @param query Query where to fetch advanced values, if omitted, use searchService.query
     */
    public createMultiInputControl(
        field: string,
        validators?: ValidatorFn[],
        asyncValidators?: AsyncValidatorFn[],
        query = this.searchService.query
    ): FormControl {
        const value = this.getValue(field, query);
        return this.createControl(value, validators, asyncValidators);
    }
Example #5
Source File: advanced.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Return a standard FormControl compatible with a text input component
     * @param field
     * @param validators optional validators to be added to the returned FormControl
     * @param asyncValidators optional asyncValidators to be added to the returned FormControl
     * @param query Query where to fetch advanced values, if omitted, use searchService.query
     */
    public createInputControl(
        field: string,
        validators?: ValidatorFn[],
        asyncValidators?: AsyncValidatorFn[],
        query = this.searchService.query
    ): FormControl {
        const value = this.getValue(field, query);
        return this.createControl(value, validators, asyncValidators);
    }
Example #6
Source File: advanced.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Return a standard FormControl compatible with a range-input component
     * @param field
     * @param validators optional validators to be added to the returned FormControl
     * @param asyncValidators optional asyncValidators to be added to the returned FormControl
     * @param query Query where to fetch advanced values, if omitted, use searchService.query
     */
    public createRangeControl(
        field: string,
        validators?: ValidatorFn[],
        asyncValidators?: AsyncValidatorFn[],
        query = this.searchService.query
    ): FormControl {
        const value = this.getRangeValue(field, query);
        return this.createControl(value, validators, asyncValidators);
    }
Example #7
Source File: advanced.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Return a standard FormControl compatible with a select component
     * @param field
     * @param validators optional validators to be added to the returned FormControl
     * @param asyncValidators optional asyncValidators to be added to the returned FormControl
     * @param query Query where to fetch advanced values, if omitted, use searchService.query
     */
    public createSelectControl(
        field: string,
        validators?: ValidatorFn[],
        asyncValidators?: AsyncValidatorFn[],
        query = this.searchService.query
    ): FormControl {
        const value = this.getValue(field, query);
        return this.createControl(value, validators, asyncValidators);
    }
Example #8
Source File: ledger-exists.validator.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
export function ledgerExists(accountingService: AccountingService): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    if (!control.dirty || !control.value || control.value.length === 0) {
      return of(null);
    }

    if (isString(control.value) && control.value.trim().length === 0) {
      return invalid;
    }

    return accountingService.findLedger(control.value, true).pipe(
      map(ledger => null),
      catchError(() => invalid),
    );
  };
}
Example #9
Source File: employee-exists.validator.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
export function employeeExists(officeService: OfficeService): AsyncValidatorFn {
  return (control: AbstractControl): Observable<any> => {
    if (!control.dirty || !control.value || control.value.length === 0) {
      return of(null);
    }

    if (isString(control.value) && control.value.trim().length === 0) {
      return invalid;
    }

    return officeService.getEmployee(control.value, true).pipe(
      map(employee => null),
      catchError(() => invalid),
    );
  };
}
Example #10
Source File: country-exists.validator.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
export function countryExists(countryService: CountryService): AsyncValidatorFn {
  return (control: AbstractControl): Observable<any> => {
    if (!control.dirty || !control.value || control.value.length === 0) {
      return of(null);
    }

    const country = control.value;
    const name: string = !!(country && typeof country === 'object') ? country.name : country;
    countryService.init();

    return of(name).pipe(
      map(searchTerm => countryService.fetchCountries(name)),
      map(countries => {
        if (countries.length === 1 && countries[0].name === name) {
          return null;
        }
        return {
          invalidCountry: true,
        };
      }),
    );
  };
}
Example #11
Source File: version.service.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
versionValidator(appNameControl: AbstractControl): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors> => {
      // if we don't have an app selected, do not validate
      if (!appNameControl.value) {
        return of(null);
      }
      return this.getVersionLog().pipe(
        map((vLog) => {
          const newVersion = control.value;
          const previousVersion = vLog[appNameControl.value];
          // check if the new version is greater than previous version
          return compareVersion(newVersion, previousVersion) === 1
            ? null
            : {
                newVersionRequired: previousVersion,
              };
        })
      );
    };
  }
Example #12
Source File: async.validator.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
/**
   * 验证用户名是否可用
   */
  legalUsername(): AsyncValidatorFn {
    return (ctrl: AbstractControl) => this.indexService.checkUsername(ctrl.value).pipe(
      map(({ data }: Result<boolean>) => (data ? null : { legalusername: true })),
      catchError(() => of(null))
    );
  }
Example #13
Source File: async.validator.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
/**
   * 验证邮箱是否可用
   */
  legalEmail(): AsyncValidatorFn {
    return (ctrl: AbstractControl) => this.indexService.checkEmail(ctrl.value).pipe(
      map(({ data }: Result<boolean>) => (data ? null : { legalemail: true })),
      catchError(() => of(null))
    );
  }
Example #14
Source File: fluid-form.component.ts    From cytoscape-angular with MIT License 6 votes vote down vote up
ngOnInit(): void {
    console.debug('FluidFormComponent this.formInfo:', JSON.stringify(this.formInfo))
    let controls = {}
    this.formInfo.fieldsets.forEach(fieldsetInfo => {
      fieldsetInfo.fieldInfos.forEach(fieldInfo => {
        let modelValue = this.model[fieldInfo.modelProperty]
        // console.log('fieldInfo.modelProperty:', fieldInfo.modelProperty, ', modelValue:', modelValue)
        const validators: ValidatorFn[] = typeof fieldInfo.validators === 'function' ? fieldInfo.validators() : fieldInfo.validators
        const asyncValidators: AsyncValidatorFn[] = typeof fieldInfo.asyncValidators === 'function' ? fieldInfo.asyncValidators() : fieldInfo.asyncValidators
        const { updateOn } = fieldInfo
        let formControl = new FormControl(modelValue, {validators, asyncValidators, updateOn })
        formControl.valueChanges.subscribe( (change) => {
          console.debug('form control change ', JSON.stringify(change), ' for prop ', fieldInfo.modelProperty,
            ', changing current model value ', this.model[fieldInfo.modelProperty], ' to ', change)
          fieldInfo.setValue(change, this.model, this.modelChange)
        })
        controls[fieldInfo.modelProperty] = formControl
      })
    })
    this.formGroup = new FormGroup(controls)
  }
Example #15
Source File: forms-typed.ts    From forms-typed with MIT License 6 votes vote down vote up
export function typedFormGroup<K, C extends Controls<K> = TypedControlsIn<K>, Key extends keyof K = keyof K>(
  controls: K extends NonGroup ? never : C,
  validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
  asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null
): TypedFormGroup<K, C> & { keys: Record<Key, string> } {
  const f = new FormGroup(controls, validatorOrOpts, asyncValidator) as any;
  f.keys = Object.keys(controls).reduce((acc, k) => ({ ...acc, [k]: k }), {});
  return f;
}
Example #16
Source File: forms-typed.ts    From forms-typed with MIT License 6 votes vote down vote up
/**
 * A helper function to create a `TypedFormArray`. It only calls the constructor of FormArray, but **strongly types** the result.
 * @param v the value to initialize our `TypedFormArray` with - same as in `new TypedFormArray(v, validators, asyncValidators)`
 * @param validators validators - same as in new `TypedFormArray(v, validators, asyncValidators)`
 * @param asyncValidators async validators - same as in `new TypedFormArray(v, validators, asyncValidators)`
 *
 * @example
 * const c = typedFormArray<string>([typedFormControl('of type string')]): TypedFormArray<string[], string>;
 * c.valueChanges // Observable<string[]>
 * c.patchValue(['s']) // expects string[]
 * c.patchValue(1) //  COMPILE TIME! type error!
 */
export function typedFormArray<T = any, K extends Array<T> = T[]>(
  controls: Array<TypedFormControl<T>>,
  validatorOrOptions?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
  asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[] | null
): TypedFormArray<K, T> {
  return new FormArray(controls, validatorOrOptions, asyncValidators) as any;
}
Example #17
Source File: forms-typed.ts    From forms-typed with MIT License 6 votes vote down vote up
/**
 * A helper function to create a `TypedFormControl`. It only calls the constructor of FormControl, but **strongly types** the result.
 * @param v the value to initialize our `TypedFormControl` with - same as in `new FormControl(v, validators, asyncValidators)`
 * @param validators validators - same as in new `FormControl(v, validators, asyncValidators)`
 * @param asyncValidators async validators - same as in `new FormControl(v, validators, asyncValidators)`
 *
 * @example
 * const c = typedFormControl<string>(): TypedFormControl<string>;
 * c.valueChanges // Observable<string>
 * c.patchValue('s') // expects string
 * c.patchValue(1) //  COMPILE TIME! type error!
 */
export function typedFormControl<T>(
  v?: T | { value: T; disabled: boolean },
  validatorsOrOptions?: ValidatorFn | ValidatorFn[] | AbstractControlOptions,
  asyncValidators?: AsyncValidatorFn | AsyncValidatorFn[]
): TypedFormControl<T> {
  return new FormControl(v, validatorsOrOptions, asyncValidators);
}
Example #18
Source File: basic-info-form.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private emailExistsValidator(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      if (!this.contact.id) {
        //if we get here it's a new contact
        return this.checkEmail(control);
      } else {
        //if the user has an ID, that means a duplicate email is okay - it could be the
        //user's original email address
        if (this.originalFormState && this.originalFormState.email == control.value) {
          //if we get here the user has the same email address as always - no conflict
          return of(null);
        } else {
          //the user changed the email address - need to check
          return this.checkEmail(control);
        }
      }
    };
  }
Example #19
Source File: form-handlers.service.ts    From open-source with MIT License 5 votes vote down vote up
asyncValidators = new Map<DynConfigId, DynHandlerFactory<AsyncValidatorFn>>();
Example #20
Source File: form-info.ts    From cytoscape-angular with MIT License 5 votes vote down vote up
// same as AbstractControlOptions
  asyncValidators: AsyncValidatorFn[] | Function
Example #21
Source File: deposit-form.component.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
private enable(formControl: FormControl, validators: ValidatorFn[], asyncValidator?: AsyncValidatorFn): void {
    formControl.enable();
    formControl.setValidators(validators);
    formControl.setAsyncValidators(asyncValidator);
    formControl.updateValueAndValidity();
  }
Example #22
Source File: tags-input.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
_inputAsyncValidator: AsyncValidatorFn;