1

浏览我看到的 angular2 api Control 类

minLength(minLength: number) : Function

我了解该功能的作用。

我想知道是否无法将验证失败时出错的描述放在函数中。

例如,我想知道该功能是否不能

minLength(minLength: number, description: string) : Function

其中描述描述了错误原因如下所示

Control firstCtrl = new Control( '', Validators.minLength(2, description: 'Minium of two characters required) );

我无法在 API 中找到任何类似的验证器。如果存在,如果可以共享链接/说明,我会很高兴。

期待看到您的反馈。

4

1 回答 1

2

没有内置的验证器采用额外的参数来描述错误。但是为此,您可以编写自己的。

让我们以内置minLength验证器为例。我们添加了第二个名为desc的参数,它将保存自定义错误消息。

class CustomValidators {
  static minLengthWithDescription(minLength: number, desc: string): Function {
    return (control: modelModule.Control): {[key: string]: any} => {
      return v.length < minLength ?
        {"minlength": {
             "requiredLength": minLength, 
             "actualLength": v.length, 
             "desc": desc // Here we pass our custom error message
        }
      } : null;
    };
  }
}

如你所见,我们几乎没有碰过原来的那个。现在就像检查我们的视图一样简单,如果错误消息存在

<form [ngFormModel]="myForm">
  <p>
    Year: <input ngControl="year"> 

    // We use the Elvis operator to check if the error exists or not
    // if exists it will print the error message
    {{myForm.controls.year.getError('minlength')?.desc}}
  </p>
</form>

最后我们设置我们想要显示的错误信息

export class App {
    year: Control = new Control('', 
        CustomValidators.minLengthWithDescription(4, 'Wrong ammount of numbers'));
}

这是一个带有示例工作的plnkr 。

于 2016-01-29T04:59:17.413 回答