1

我创建了用于验证输入值的指令。我需要在输入一些字符时,我的输入/表单变得有效。这是我的代码,但它不起作用。

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors} from '@angular/forms';

const regExp = new RegExp('(>|<)+');

@Directive({
    selector: '[validator]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: ValidatorDirective,
        multi: true
    }]
})

export class ValidatorDirective {
    @Input('validator') input;

    constructor() {

    }

    validate (control: AbstractControl): ValidationErrors {
        const value = control.value;
        const isValid = regExp.test(value);

        return isValid ? null : {
            validator: {
                valid: false
            }
        };
    }
}

谢谢您的帮助。祝你今天过得愉快。

4

1 回答 1

1

使用[validator][ngModel]将在您的情况下解决问题,因为您不需要为此指令输入

像这样

import {AbstractControl, ValidatorFn, Validator, FormControl, NG_VALIDATORS} from "@angular/forms";
import {Directive} from '@angular/core';


const regExp = new RegExp('(>|<)+');
function validateregex(): ValidatorFn {
  return (c : AbstractControl) => {

    const isValid = regExp.test(c.value);
    console.log("Valid"+isValid);
    //let isValid = c.value === 'Rahul';
    if(isValid){
      return null;
    }else{
      return {
        validator: {
          valid: false
        }
      };
    }

  }
}

@Directive({
  selector: '[regex][ngModel]',
  providers: [{
    provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true
  }]
})

export class ValidatorDirective implements Validator{

  validator: ValidatorFn;

  constructor() {
    this.validator = validateregex();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

}

将此指令添加到declarations数组Ngmodule ValidatorDirective,

相同链接的工作示例。

于 2017-08-27T08:35:40.977 回答