typescript – 模型值不会在角度2中自动修剪

前端之家收集整理的这篇文章主要介绍了typescript – 模型值不会在角度2中自动修剪前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用角度2表单验证,我在文本框中设置了所需的验证,当我在文本框中输入任何内容时,它显示所需的错误消息它是可以的但是当我只输入空格时它没有显示所需的错误消息,这意味着角度2没有修剪模型值.

在角度1.x中,它会自动修剪模型值,但在角度2中,我看不到此功能.

好吧,有一个 long discussion on github,结果如下:我们必须实现自己的验证器.

这是我到目前为止使用的:

import { ValidatorFn,AsyncValidatorFn,Validators as V,FormControl } from '@angular/forms';

// the need in this validators is the non-trimming angular standard behavior
// see https://github.com/angular/angular/issues/8503
export class Validators {

  public static required(control: FormControl) {
    if (!control.value || typeof control.value === 'string' && !control.value.trim()) {
      return {
        required: true
      };
    }

    return null;
  }

  public static minLength(length: number): ValidatorFn {
    return (control: FormControl) => {
      if (!control.value || typeof control.value === 'string' && control.value.trim().length < length) {
        return {
          minlength: true
        };
      }

      return null;
    };
  }

  public static maxLength(length: number): ValidatorFn {
    return (control: FormControl) => {
      if (control.value && typeof control.value === 'string' && control.value.trim().length > length) {
        return {
          maxlength: true
        };
      }

      return null;
    };
  }

  public static pattern(pattern: string): ValidatorFn {
    return V.pattern(pattern);
  }

  public static minAmount(amount: number): ValidatorFn {
    return (control: FormControl) => {
      if (control.value && control.value.length < amount) {
        return {
          minamount: true
        };
      }

      return null;
    };
  }

  public static maxAmount(amount: number): ValidatorFn {
    return (control: FormControl) => {
      if (control.value && control.value.length > amount) {
        return {
          maxamount: true
        };
      }

      return null;
    };
  }

  public static compose(validators: ValidatorFn[]): ValidatorFn {
    return V.compose(validators);
  }

  public static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn {
    return V.composeAsync(validators);
  }

};

这模仿了字符串输入的标准maxLength,minLength和必需的验证,但是修剪和代理标准的其他功能.

要使用它,只需导入验证器而不是@ angular / forms one,例如:

import { FormControl } from '@angular/forms';
import { Validators } from 'path/to/validators';

...
let control = new FormControl('',Validators.compose(
  Validators.required,Validators.minLength(6)
));
...

这可能不会修剪模型,但它解决了请求中指定的验证问题.

猜你在找的Angularjs相关文章