@angular/forms#ValidatorFn TypeScript Examples

The following examples show how to use @angular/forms#ValidatorFn. 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: url-validator.directive.ts    From one-platform with MIT License 6 votes vote down vote up
urlValidator(): ValidatorFn {
    return (control: FormControl) => {
      const url = control.value;
      try {
        new URL(url);
        return null;
      } catch (e) {
        return { urlValidator: { valid: false } };
      }
    };
  }
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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: forbitten-email-validator.directive.ts    From mns with MIT License 6 votes vote down vote up
export function forbittenEmailValidator(): ValidatorFn {

  return (control: AbstractControl): { [key: string]: any } | null => {


    // valid email pattern
    const emailPattern = '^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$';
    const regExp = new RegExp(emailPattern);
    // Execute Validation!! Cool
    const isOkay = regExp.test(control.value);
    console.log(' ISOkay = ' + isOkay);
    return !isOkay ? { forbiddenEmail: { value: control.value } } : null;
  };
}
Example #12
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 #13
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 #14
Source File: sync.validator.ts    From onchat-web with Apache License 2.0 6 votes vote down vote up
/**
   * 比较表单中N个字段的值是否相等
   * @param ctrl 字段名
   * @param ctrls 更多的字段名
   */
  static equal(ctrl: string, ...ctrls: string[]): ValidatorFn {
    return (form: FormGroup) => {
      for (const c of ctrls) {
        if (form.get(ctrl).value !== form.get(c).value) {
          return { equal: true };
        }
      }

      return null;
    };
  }
Example #15
Source File: validators.ts    From digital-bank-ui with Mozilla Public License 2.0 6 votes vote down vote up
static scale(scale: number): ValidatorFn {
    return (c: AbstractControl): ValidationErrors | null => {
      if (!isEmptyInputValue(c.value)) {
        const stringValue = String(c.value);

        const valueChunks = stringValue.split('.');

        if (valueChunks.length === 1 && scale === 0) {
          return null;
        }

        if (valueChunks.length === 2 && valueChunks[1].length === scale) {
          return null;
        }

        return {
          scale: {
            valid: false,
            value: scale,
          },
        };
      }
      return null;
    };
  }
Example #16
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 #17
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 #18
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 #19
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 #20
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 #21
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;
    };
  }
Example #22
Source File: url-validator.directive.ts    From one-platform with MIT License 5 votes vote down vote up
validator: ValidatorFn;
Example #23
Source File: login.component.ts    From homebridge-nest-cam with GNU General Public License v3.0 5 votes vote down vote up
function containsValidator(start: string): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const contains = control.value.includes(start);
    return contains ? null : { contains: { value: control.value } };
  };
}
Example #24
Source File: same-value.validator.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
sameValueValidator = (value: string): ValidatorFn => (control: AbstractControl): { [key: string]: any } | null =>
  value !== control.value
    ? { sameValue: false }
    : null
Example #25
Source File: transfer-modal.component.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
function correctAddressValidator(blockchainAdapter: EthLikeWeb3Public): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const isAddressCorrect = blockchainAdapter.isAddressCorrect(control.value);
    return isAddressCorrect ? null : { wrongAddress: control.value };
  };
}
Example #26
Source File: afterDate.validator.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('afterDate', () => {
  let control: AbstractControl;
  let validator: ValidatorFn;
  let dateToCompare: Date;
  let date: Date;

  beforeEach(() => {
    dateToCompare = new Date();
    control = mock(AbstractControl);
    validator = afterDateValidator(dateToCompare);
  });

  describe('date to compare is not a valid date', () => {
    it('throws an error', () => {
      expect(() => afterDateValidator(new Date('xx'))).toThrow();
    });
  });

  describe('date is before the specified date', () => {
    beforeEach(() => {
      date = subDays(dateToCompare, 10);
      when(control.value).thenReturn(format(date, 'yyyy-MM-dd'));
    });

    it('adds a afterDate error', () => {
      expect(validator(instance(control))).toEqual(jasmine.any(Object));
    });

    it('includes the date to compare against', () => {
      expect(validator(instance(control)).afterDate).toEqual(
        jasmine.objectContaining({
          required: format(dateToCompare, dateFormat),
        }),
      );
    });

    it('includes the date that was entered', () => {
      expect(validator(instance(control)).afterDate).toEqual(
        jasmine.objectContaining({
          actual: format(date, dateFormat),
        }),
      );
    });
  });

  it('returns null if the date is null', () => {
    when(control.value).thenReturn(null);

    expect(validator(instance(control))).toBe(null);
  });

  it('returns null if the date is not a valid date', () => {
    when(control.value).thenReturn(new Date('not a date'));

    expect(validator(instance(control))).toBe(null);
  });

  it('returns null if date is after the specified date', () => {
    date = addDays(dateToCompare, 10);
    when(control.value).thenReturn(format(date, 'yyyy-MM-dd'));

    expect(validator(instance(control))).toEqual(null);
  });
});
Example #27
Source File: tags-input.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
// 0: use default style const value, > 1: for ```tagClassFn``` maybe affect lineHeight

  _inputValidator: ValidatorFn;
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: color-input.component.ts    From angular-material-components with MIT License 5 votes vote down vote up
/** The combined form control validator for this input. */
  private _validator: ValidatorFn | null =
    Validators.compose([]);