Files
angular-docs-cn/modules/angular2/src/forms/validators.js
T

38 lines
1.2 KiB
JavaScript
Raw Normal View History

2015-02-11 11:10:31 -08:00
import {isBlank, isPresent} from 'angular2/src/facade/lang';
import {List, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
2015-03-09 17:41:49 +01:00
import * as modelModule from './model';
2015-02-11 11:10:31 -08:00
2015-03-09 17:41:49 +01:00
export function required(c:modelModule.Control) {
2015-02-24 11:59:10 -08:00
return isBlank(c.value) || c.value == "" ? {"required" : true} : null;
2015-02-11 11:10:31 -08:00
}
2015-03-09 17:41:49 +01:00
export function nullValidator(c:modelModule.Control) {
2015-02-11 11:10:31 -08:00
return null;
}
export function compose(validators:List<Function>):Function {
2015-03-09 17:41:49 +01:00
return function(c:modelModule.Control) {
2015-02-24 11:59:10 -08:00
var res = ListWrapper.reduce(validators, (res, validator) => {
2015-02-11 11:10:31 -08:00
var errors = validator(c);
return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res;
}, {});
2015-02-24 11:59:10 -08:00
return StringMapWrapper.isEmpty(res) ? null : res;
2015-02-11 11:10:31 -08:00
}
}
2015-03-09 17:41:49 +01:00
export function controlGroupValidator(c:modelModule.ControlGroup) {
2015-02-11 11:10:31 -08:00
var res = {};
StringMapWrapper.forEach(c.controls, (control, name) => {
if (c.contains(name) && isPresent(control.errors)) {
2015-02-25 12:54:27 -08:00
StringMapWrapper.forEach(control.errors, (value, error) => {
if (! StringMapWrapper.contains(res, error)) {
res[error] = [];
}
ListWrapper.push(res[error], control);
});
2015-02-11 11:10:31 -08:00
}
});
return StringMapWrapper.isEmpty(res) ? null : res;
}