@angular/forms#ValidationErrors TypeScript Examples

The following examples show how to use @angular/forms#ValidationErrors. 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: validators.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
static greaterThanEquals(firstValue: string, secondValue: string) {
    return (group: FormGroup): ValidationErrors | null => {
      const firstNumber: number = Number(group.controls[firstValue].value);
      const secondNumber: number = Number(group.controls[secondValue].value);

      if (firstNumber == null || secondNumber == null) {
        return null;
      }

      if (firstNumber > secondNumber) {
        return {
          greaterThanEquals: true,
        };
      }

      return null;
    };
  }
Example #2
Source File: dyn-providers.ts    From open-source with MIT License 6 votes vote down vote up
defaultAsyncValidators: DynControlAsyncValidator[] = [
  {
    id: 'RELATED',
    fn: (node: DynTreeNode, config: DynControlRelated, validator: ValidatorFn = Validators.required) => {
      return (control: AbstractControl): Observable<ValidationErrors | null> => {
        return node.root.loaded$.pipe(
          first(Boolean),
          switchMap(() => relatedConditionFn(config)(node)),
          map(hasMatch => hasMatch ? validator(control) : null),
          first(),
        );
      }
    }
  },
].map(
  mapPriority<DynControlAsyncValidator>()
)
Example #3
Source File: feedback.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
usernameFeedback: ValidationFeedback = (errors: ValidationErrors) => {
  if (!errors) { return; }
  if (errors.required) {
    return '用户名不能为空!';
  }
  if (errors.pattern) {
    return '用户名只能包含字母/汉字/数字/下划线/横杠!';
  }
  if (errors.minlength || errors.maxlength) {
    return `用户名长度必须在${USERNAME_MIN_LENGTH}~${USERNAME_MAX_LENGTH}位字符之间!`;
  }
  if (errors.legalusername) {
    return '该用户名已被占用!';
  }
}
Example #4
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 #5
Source File: afterDate.validator.ts    From canopy with Apache License 2.0 6 votes vote down vote up
export function afterDateValidator(dateToCompare: Date): ValidatorFn {
  if (!isValid(dateToCompare)) {
    throw new Error('afterDateValidator: dateToCompare is not a valid date');
  }

  return (control: AbstractControl): ValidationErrors | null => {
    const date = parseISO(control.value);

    return !isValid(date) || isAfter(date, dateToCompare)
      ? null
      : {
        afterDate: {
          required: format(dateToCompare, dateFormat),
          actual: format(date, dateFormat),
        },
      };
  };
}
Example #6
Source File: validators.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
static matchValues(firstValue: string, secondValue: string) {
    return (group: FormGroup): ValidationErrors | null => {
      const val1 = group.controls[firstValue];
      const val2 = group.controls[secondValue];

      if (val1.value !== val2.value) {
        return {
          'mismatch': true,
        };
      }

      return null;
    };
  }
Example #7
Source File: validation.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * A pattern validator based on Angular's `Validators.email` with support for value arrays.
     *
     * @param control The control to validate.
     * @returns The result.
     */
    static emailValidation(control: AbstractControl): ValidationErrors | null {
        if (isEmptyInputValue(control.value)) {
            return null;  // don't validate empty values to allow optional controls
        }

        let values: any[] = [];
        values = processInputValue(control.value);

        for (const value of values) {
            if (!EMAIL_REGEXP.test(value)) {
                return {email: true};
            }
        }

        return null;
    }
Example #8
Source File: token-verify.service.ts    From HeartBeat with MIT License 6 votes vote down vote up
verifyTokenValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors | null => {
      const invalid = Object.keys(group.controls)
        .map((control) => group.get(control))
        .filter((instance) => instance instanceof FormGroup)
        .find((g) => {
          return g.get('verifyToken').value === 'Verify';
        });
      return invalid ? { tokenVerify: true } : null;
    };
  }
Example #9
Source File: ion-intl-tel-input.directive.ts    From ion-intl-tel-input with MIT License 6 votes vote down vote up
static phone(control: AbstractControl): ValidationErrors | null {
    const error = { phone: true };
    let phoneNumber: PhoneNumber;

    if (!control.value) {
      return error;
    }

    try {
      phoneNumber = PhoneNumberUtil.getInstance().parse(
        control.value.nationalNumber,
        control.value.isoCode
      );
    } catch (e) {
      return error;
    }

    if (!phoneNumber) {
      return error;
    } else {
      if (
        !PhoneNumberUtil.getInstance().isValidNumberForRegion(
          phoneNumber,
          control.value.isoCode
        )
      ) {
        return error;
      }
    }
  }
Example #10
Source File: password-validation.directive.ts    From dating-client with MIT License 6 votes vote down vote up
passwordValidation = (control: FormGroup): ValidationErrors | null => {
  const password = control.get('password')?.value;
  const confirmPassword = control.get('confirmPassword')?.value;
  const error = { passwordsDontMatch: true };

  if (password === null || confirmPassword === null) {
    return error;
  }

  if (password === confirmPassword) {
    return null;
  }
  return error;
}
Example #11
Source File: beforeDate.validator.ts    From canopy with Apache License 2.0 6 votes vote down vote up
export function beforeDateValidator(dateToCompare: Date): ValidatorFn {
  if (!isValid(dateToCompare)) {
    throw new Error('beforeDateValidator: dateToCompare is not a valid date');
  }

  return (control: AbstractControl): ValidationErrors | null => {
    const date = parseISO(control.value);

    return !isValid(date) || isBefore(date, dateToCompare)
      ? null
      : {
        beforeDate: {
          required: format(dateToCompare, dateFormat),
          actual: isValid(date)
            ? format(date, dateFormat)
            : control.value,
        },
      };
  };
}
Example #12
Source File: basic-info-form.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private checkEmail(control: AbstractControl): Observable<ValidationErrors | null> {
    if (control.value && (<string>control.value).trim().length > 0) {
      return of(control.value).pipe(
        delay(500),
        switchMap((email) => this.contactService.doesEmailExist(email).pipe(
          map(emailExists => emailExists ? { emailExists: true } : null)
        ))
      );
    } else {
      return of(null);
    }
  }
Example #13
Source File: futureDate.validator.ts    From canopy with Apache License 2.0 6 votes vote down vote up
export function futureDateValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const date = parseISO(control.value);

    return !isValid(date) || isFuture(parseISO(control.value))
      ? null
      : { futureDate: true };
  };
}
Example #14
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 #15
Source File: max-size.validator.ts    From angular-material-components with MIT License 6 votes vote down vote up
/**
 * Validator for size of file
 * @param max Max of size of file (in bytes)
 */
export function MaxSizeValidator(max: number): ValidatorFn {
    return (ctrl: AbstractControl): ValidationErrors | null => {
        max = Number(max);
        if (isNaN(max)) {
            throw 'MaxSizeValidator: max of size of file is invalid';
        }
        if (!ctrl.value) return null;
        let files: File[] = ctrl.value;
        if (!Array.isArray(ctrl.value)) {
            files = [ctrl.value];
        }
        if(!files.length) return null;
        const add = (a: any, b: any): number => a + b;
        const sumSize = files.map(x => x.size).reduce(add);
        if (sumSize > max) {
            return {
                maxSize: true
            };
        }
        return null;
    }
}
Example #16
Source File: pastDate.validator.ts    From canopy with Apache License 2.0 6 votes vote down vote up
export function pastDateValidator(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const date = parseISO(control.value);

    return !isValid(date) || isPast(date)
      ? null
      : { pastDate: true };
  };
}
Example #17
Source File: validators.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
export function allowEmptybitcoinAddressValidator(network: string | undefined): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value === '') {
      // console.debug('allowEmptybitcoinAddressValidator() control.value:', control.value)
      // control.markAsUntouched()
      control.markAsPristine()
      return null
    }
    const allowed = validate(control.value, <Network>network)
    return allowed ? null : { addressInvalid: { value: control.value } }
  }
}
Example #18
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 #19
Source File: validators.ts    From alauda-ui with MIT License 6 votes vote down vote up
validate(control: AbstractControl): ValidationErrors {
    if (!this.selectRef.contentOptions || !control.value) {
      return;
    }
    return !this.includes
      ? null
      : AuiSelectValidators.includes(
          this.selectRef.contentOptions
            .filter(option => !option.disabled)
            .map(option => option.value),
          this.trackFn,
        )(control);
  }
Example #20
Source File: accept.validator.ts    From angular-material-components with MIT License 6 votes vote down vote up
/**
 * 
 * @param accept Allowable type of file
 */
export function AcceptValidator(accept: string): ValidatorFn {
    return (ctrl: AbstractControl): ValidationErrors | null => {
        if (!accept) {
            throw ('AcceptValidator: allowable type of file can not be empty');
        }

        if (ctrl.value == null) return null;

        if (!accept.includes(ctrl.value.type)) {
            return {
                accept: true
            };
        }

        return null;

    }
}
Example #21
Source File: validators.ts    From bitcoin-s-ts with MIT License 5 votes vote down vote up
export function regexValidator(regex: RegExp): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const allowed = regex.test(control.value)
    return allowed ? null : { regexInvalid: { value: control.value }}
  }
}
Example #22
Source File: datetime-input.ts    From angular-material-components with MIT License 5 votes vote down vote up
/** @docs-private */
    validate(c: AbstractControl): ValidationErrors | null {
        return this._validator ? this._validator(c) : null;
    }
Example #23
Source File: validators.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
static email(control: AbstractControl): ValidationErrors | null {
    if (isEmptyInputValue(control.value)) {
      return null;
    }

    return EMAIL_REGEXP.test(control.value) ? null : { 'email': true };
  }
Example #24
Source File: validators.ts    From bitcoin-s-ts with MIT License 5 votes vote down vote up
export function bitcoinAddressValidator(network: string | undefined): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const allowed = validate(control.value, <Network>network)
    return allowed ? null : { addressInvalid: { value: control.value } }
  }
}
Example #25
Source File: add-edit-advance-request.page.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
currencyObjValidator(c: FormControl): ValidationErrors {
    if (c.value && c.value.amount && c.value.currency) {
      return null;
    }
    return {
      required: false,
    };
  }
Example #26
Source File: color-input.component.ts    From angular-material-components with MIT License 5 votes vote down vote up
validate(c: AbstractControl): ValidationErrors | null {
    return this._validator ? this._validator(c) : null;
  }
Example #27
Source File: validators.ts    From digital-bank-ui with Mozilla Public License 2.0 5 votes vote down vote up
static isNumber(control: AbstractControl): ValidationErrors | null {
    if (control.value && isNaN(control.value)) {
      return {
        isNumber: true,
      };
    }
    return null;
  }
Example #28
Source File: new-announcement.component.ts    From bitcoin-s-ts with MIT License 5 votes vote down vote up
/** Validators */

function regexValidator(regex: RegExp): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const allowed = regex.test(control.value)
    return allowed ? null : { regexInvalid: { value: control.value }}
  }
}
Example #29
Source File: ion-intl-tel-input.directive.ts    From ion-intl-tel-input with MIT License 5 votes vote down vote up
validate(control: AbstractControl): ValidationErrors | null {
    return IonIntlTelInputValidators.phone(control);
  }