@angular/forms#AbstractControl TypeScript Examples

The following examples show how to use @angular/forms#AbstractControl. 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: activity-form.component.ts    From careydevelopmentcrm with MIT License 7 votes vote down vote up
private startDateValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      this.startDateChanged();
      this.endDateChanged();

      if (this.selectedActivityType) {
        if (!control.value || control.value.toString().trim() == '') {
          return { 'invalid': true };
        } else {
          let today: number = Date.now();
          let difference = Math.abs(today - this.currentStartDate);
          if (difference > maximumTimeSpan) {
            return { 'threshold': true };
          }
        }
      }

      return null;
    };
  }
Example #2
Source File: form-validator-util.ts    From data-annotator-for-machine-learning with Apache License 2.0 7 votes vote down vote up
static markControlsAsTouched(formElement: AbstractControl): void {
    if (formElement instanceof FormControl) {
      formElement.markAsTouched();
    } else if (formElement instanceof FormGroup) {
      Object.keys(formElement.controls).forEach((key) => {
        this.markControlsAsTouched(formElement.get(key));
      });
    } else if (formElement instanceof FormArray) {
      formElement.controls.forEach((control) => {
        this.markControlsAsTouched(control);
      });
    }
  }
Example #3
Source File: app.component.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
// function capitalFirstChar(str: string): string {
//   if (!str) {
//     return '';
//   }
//   const capitalLetter = str.slice(0, 1).toUpperCase();
//   const restOfTheString = str.slice(1);
//
//   return `${capitalLetter}${restOfTheString}`;
// }

export function maxBn(tokenHelper: TokenHelper, balance: BigNumber, decimals: number): ValidatorFn {

    return (control: AbstractControl): { [key: string]: any } | null => {
        const parsedAsset = tokenHelper.parseUnits(control.value, decimals);
        const forbidden = parsedAsset.gt(balance);
        return forbidden ? {maxBalance: {value: control.value}} : null;
    };
}
Example #4
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 #5
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 #6
Source File: validators.ts    From alauda-ui with MIT License 6 votes vote down vote up
static includes<T>(
    options: T[],
    trackFn: TrackFn<T> = val => val,
  ): ValidatorFn {
    return (control: AbstractControl) =>
      options.some(option => trackFn(option) === trackFn(control.value))
        ? null
        : {
            includes: control.value,
          };
  }
Example #7
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 #8
Source File: new-announcement.component.ts    From bitcoin-s-ts with MIT License 6 votes vote down vote up
function conditionalValidator(predicate: any, validator: any): ValidatorFn {
  return (formControl: AbstractControl) => {
    if (!formControl.parent) {
      return null
    }
    if (predicate()) {
      return validator(formControl);
    }
    return null
  }
}
Example #9
Source File: send.component.ts    From blockcore-hub with MIT License 6 votes vote down vote up
private buildSendForm(): void {
        this.sendForm = this.fb.group({
            address: ['', Validators.compose([Validators.required, Validators.minLength(26)])],
            amount: ['', Validators.compose([Validators.required, Validators.pattern(/^([0-9]+)?(\.[0-9]{0,8})?$/), Validators.min(0.00001), (control: AbstractControl) => Validators.max((this.totalBalance - this.estimatedFee) / 100000000)(control)])],
            fee: ['medium', Validators.required],
            password: ['', Validators.required],
            shuffleOutputs: [true],
            opreturndata: ['', Validators.compose([Validators.maxLength(this.appState.activeChain.opreturndata)])], // TODO: This is maxLength for ASCII, with UNICODE it can be longer but node will throw error then. Make a custom validator that encodes UTF8 to bytes.
            opreturnamount: ['', Validators.compose([Validators.pattern(/^([0-9]+)?(\.[0-9]{0,8})?$/)])],
        });

        this.sendForm.valueChanges.pipe(debounceTime(300))
            .subscribe(data => this.onValueChanged(data));
    }
Example #10
Source File: activity-form.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
private endDateValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      this.startDateChanged();
      this.endDateChanged();

      if (this.selectedActivityType && this.selectedActivityType.usesEndDate) {
        if (!control.value || control.value.toString().trim() == '') {
          return { 'invalid': true };
        } else if (this.currentStartDate > this.currentEndDate) {
          return { 'sequence': true };
        } else if (Math.abs(this.currentStartDate - this.currentEndDate) > maxAppointmentLength) {
          return { 'maxAppointmentLength' : true };
        }
      }

      return null;
    };
  }
Example #11
Source File: version-number.ts    From attack-workbench-frontend with Apache License 2.0 6 votes vote down vote up
/**
 * form field validator checking if the version number is formatted correctly
 */
export function versionNumberFormatValidator(): ValidatorFn {
    const pattern = /^(\d+\.)*\d+$/;
    return (control: AbstractControl): {[key:string]: any} | null => {
        const valid = pattern.test(control.value);
        return !valid ? { "invalidVersionFormat": { value: control.value }} : null;
    }
}
Example #12
Source File: must-match.validator.ts    From angular-11-crud-example with MIT License 6 votes vote down vote up
// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
    return (group: AbstractControl) => {
        const formGroup = <FormGroup>group;
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
            // return if another validator has already found an error on the matchingControl
            return null;
        }

        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
        } else {
            matchingControl.setErrors(null);
        }

        return null;
    }
}
Example #13
Source File: send.component.ts    From EXOS-Core with MIT License 6 votes vote down vote up
private buildSendForm(): void {
        this.sendForm = this.fb.group({
            address: ['', Validators.compose([Validators.required, Validators.minLength(26)])],
            amount: ['', Validators.compose([Validators.required, Validators.pattern(/^([0-9]+)?(\.[0-9]{0,8})?$/), Validators.min(0.00001), (control: AbstractControl) => Validators.max((this.totalBalance - this.estimatedFee) / 100000000)(control)])],
            fee: ['medium', Validators.required],
            password: ['', Validators.required]
        });

        this.sendForm.valueChanges.pipe(debounceTime(300))
            .subscribe(data => this.onValueChanged(data));
    }
Example #14
Source File: add-edit-mileage.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
customDateValidator(control: AbstractControl) {
    const today = new Date();
    const minDate = moment(new Date('Jan 1, 2001'));
    const maxDate = moment(new Date(today)).add(1, 'day');
    const passedInDate = control.value && moment(new Date(control.value));
    if (passedInDate) {
      return passedInDate.isBetween(minDate, maxDate)
        ? null
        : {
            invalidDateSelection: true,
          };
    }
  }
Example #15
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 #16
Source File: forbitten-email-validator.directive.ts    From mns with MIT License 6 votes vote down vote up
// Return typ ?
  // Control ie. input element
  validate(control: AbstractControl): { [key: string]: any } | null {
    console.log('Directive--> ' + control.errors);
    // Nice.. see how to  define RegExp object in angular

    // Execute validation logic --> ValidationErrors
    const response = this.forbittenEmail ? forbittenEmailValidator()(control) : null;
    // const l = JSON.stringify(response);
    // console.log(' Response= ' + l + ' ' + response.forbiddenEmail);
    return response;
  }
Example #17
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 #18
Source File: utils.ts    From bind-query-params with MIT License 6 votes vote down vote up
export function defsToParams(defs: QueryParamDef[], group: AbstractControl) {
  return defs.map((def) => {
    return {
      queryKey: def.queryKey,
      value: group.get(def.path)!.value,
    };
  });
}
Example #19
Source File: app.component.ts    From edit-in-place with MIT License 6 votes vote down vote up
toGroups(): AbstractControl[] {
    return this.accounts.map((account) => {
      return new FormGroup({
        name: new FormControl(account.name),
        role: new FormControl(account.role),
        isActive: new FormControl(account.isActive),
      });
    });
  }
Example #20
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 #21
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 #22
Source File: validators.directive.ts    From workflow-editor with Educational Community License v2.0 6 votes vote down vote up
validate(control: AbstractControl): {[key: string]: any} {
    const parser: Parser = new Parser(
      Grammar.fromCompiled(grammar),
      { keepHistory: true }
    );
    try {
      parser.feed(control.value);
      return null;
    } catch (err) {
      return {invalidIfCond: {notvalid: true, msg: err.message.split("Instead")[0]}};
    }
  }
Example #23
Source File: manage-baskets.ts    From sba-angular with MIT License 6 votes vote down vote up
constructor(
        @Inject(MODAL_MODEL) public model: ManageBasketsModel,
        public savedQueryService: SavedQueriesService,
        public basketsService: BasketsService,
        public appService: AppService
    ) {
        this.reordering = false;

        this.nameValidators = [
            Validators.required,
            (control: AbstractControl) => {
                const modelControl = control.root.get("model");
                if (modelControl) {
                    for (const item of this.model.baskets) {
                        if (modelControl.value === item) {
                            continue;
                        }
                        if (control.value === item.name) {
                            return {
                                unique: true
                            };
                        }
                    }
                }
                return null;
            }
        ];
    }
Example #24
Source File: patternValidator.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export function patternValidator(regexp: RegExp): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    const value = control.value;
    if (value === '') {
      return null;
    }
    return !regexp.test(value) ? { patternInvalid: { regexp } } : null;
  };
}
Example #25
Source File: create.component.ts    From StraxUI with MIT License 6 votes vote down vote up
private setDynamicPassphraseValidators(passphraseValue: string, controls: { passphrase: AbstractControl; passphraseConfirmation: AbstractControl }): void {
    const { passphrase, passphraseConfirmation } = controls;

    if (passphraseValue.length) {
      // passphrase and confirmation should be required if passphrase is not null
      // eslint-disable-next-line @typescript-eslint/unbound-method
      passphrase.setValidators(Validators.required);
      // eslint-disable-next-line @typescript-eslint/unbound-method
      passphraseConfirmation.setValidators(Validators.required);

      // Update form group validators to include MatachPassword and MatchPassphrase
      this.createWalletForm.setValidators([
        // eslint-disable-next-line @typescript-eslint/unbound-method
        PasswordValidationDirective.MatchPassword,
        // eslint-disable-next-line @typescript-eslint/unbound-method
        PasswordValidationDirective.MatchPassphrase
      ]);
    } else { // Else, passphrase field is null, clear validators
      // clear passphrase validators, errors, mark pristine
      passphrase.clearValidators();
      passphrase.setErrors(null);
      passphrase.markAsPristine();

      // clear confirmation validators, errors, mark pristine
      passphraseConfirmation.setValue(null);
      passphraseConfirmation.clearValidators();
      passphraseConfirmation.setErrors(null);
      passphraseConfirmation.markAsPristine();

      // clear then set MatchPassword validator on form
      this.createWalletForm.clearValidators();
      // eslint-disable-next-line @typescript-eslint/unbound-method
      this.createWalletForm.setValidators(PasswordValidationDirective.MatchPassword);
    }

    this.createWalletForm.updateValueAndValidity();
  }
Example #26
Source File: no-whitespace.validator.ts    From jira-clone-angular with MIT License 6 votes vote down vote up
// eslint-disable-next-line @typescript-eslint/naming-convention
export function NoWhitespaceValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    let controlVal = control.value;
    if (typeof controlVal === 'number') {
      controlVal = `${controlVal}`;
    }
    const isWhitespace = (controlVal || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { whitespace: 'value is only whitespace' };
  };
}
Example #27
Source File: profile-details-edit.component.ts    From tuxedo-control-center with GNU General Public License v3.0 6 votes vote down vote up
function minControlValidator(comparisonControl: AbstractControl): ValidatorFn {
    return (thisControl: AbstractControl): { [key: string]: any } | null => {
        let errors = null;
        if (thisControl.value < comparisonControl.value) {
            errors = { min: comparisonControl.value, actual: thisControl.value };
        }
        return errors;
    };
}
Example #28
Source File: dataset-validator.ts    From data-annotator-for-machine-learning with Apache License 2.0 6 votes vote down vote up
static modelName(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      if (!control.parent) {
        return null;
      }

      if (DatasetValidator.isEmpty(control.value)) {
        return { msg: { value: DatasetValidator.REQUIRED_FIELD } };
      }

      const pattern = `^[a-zA-Z0-9 _\\-\\.]+$`;
      const argRegEx = new RegExp(pattern, 'g');
      if (!control.value.match(argRegEx)) {
        return {
          msg: {
            value:
              'Wrong format! Model name only allow letters, digits, dots, underscores and hyphen',
          },
        };
      }
      return null;
    };
  }