Angular2 - Directive - validators

之前写了min-Length的解读
http://dreambo8563.github.io/2015/12/23/Angular2-minLenght/

这里把其他几个也一起了

  • 先来maxlength
const MAX_LENGTH_VALIDATOR = CONST_EXPR(
new Provider(NG_VALIDATORS, {useExisting: forwardRef(() => MaxLengthValidator), multi: true}));

/**
* A directive which installs the {@link MaxLengthValidator} for any `ngControl, `ngFormControl`,
* or control with `ngModel` that also has a `maxlength` attribute.
*/
@Directive({
selector: '[maxlength][ngControl],[maxlength][ngFormControl],[maxlength][ngModel]',
providers: [MAX_LENGTH_VALIDATOR]
})
export class MaxLengthValidator implements Validator {
private _validator: Function;

constructor(@Attribute("maxlength") maxLength: string) {
this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
}

validate(c: Control): {[key: string]: any} { return this._validator(c); }
}

Validators.maxLength

static maxLength(maxLength: number): Function {
return (control: modelModule.Control): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length > maxLength ?
{"maxlength": {"requiredLength": maxLength, "actualLength": v.length}} :
null;
};
}
  • @Attribute(“maxlength”) maxLength - 拿到属性值
  • maxLength 返回一个function 给_validator。 里面做了基本检查。解读可以看Min-Length的,几乎一样
  • validate方法

以下开始扒皮。。。

在model里会有updateValueAndValidity 方法。里面有这样的代码。也是最外层来检查是否有error

model.ts

this._errors = this._runValidator();
...
private _runValidator() { return isPresent(this.validator) ? this.validator(this) : null; }

传入了this(本control) 给如下的get validator

xxx.ts (lots of controls)例如 ng_model.ts

get validator(): Function { return composeValidators(this._validators); }

composeValidators 其实就是把多个validator搞到一起处理

shared.ts

export function composeValidators(validators: /* Array<Validator|Function> */ any[]): Function {
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
}

这里是一般的处理,并直接把maxlength等validator 指令中的validate()方法暴露出来执行

normalize_validator.ts

import {Validator} from './validators';

export function normalizeValidator(validator: Function | Validator): Function {
if ((<Validator>validator).validate !== undefined) {
return (c) => (<Validator>validator).validate(c);
} else {
return <Function>validator;
}
}

这个很细了,required就没必要写了