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-31 22:47:11 +00:00
|
|
|
/**
|
2015-04-10 11:15:01 -07:00
|
|
|
* Provides a set of validators used by form controls.
|
|
|
|
*
|
|
|
|
* # Example
|
|
|
|
*
|
|
|
|
* ```
|
|
|
|
* var loginControl = new Control("", Validators.required)
|
|
|
|
* ```
|
|
|
|
*
|
2015-04-10 12:45:02 +02:00
|
|
|
* @exportedAs angular2/forms
|
2015-03-31 22:47:11 +00:00
|
|
|
*/
|
2015-03-19 14:21:40 -07:00
|
|
|
export class Validators {
|
|
|
|
static required(c:modelModule.Control) {
|
|
|
|
return isBlank(c.value) || c.value == "" ? {"required": true} : null;
|
|
|
|
}
|
2015-02-11 11:10:31 -08:00
|
|
|
|
2015-03-24 13:45:47 -07:00
|
|
|
static nullValidator(c:any) {
|
2015-03-19 14:21:40 -07:00
|
|
|
return null;
|
2015-02-11 11:10:31 -08:00
|
|
|
}
|
|
|
|
|
2015-03-19 14:21:40 -07:00
|
|
|
static compose(validators:List<Function>):Function {
|
|
|
|
return function (c:modelModule.Control) {
|
|
|
|
var res = ListWrapper.reduce(validators, (res, validator) => {
|
|
|
|
var errors = validator(c);
|
|
|
|
return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res;
|
|
|
|
}, {});
|
|
|
|
return StringMapWrapper.isEmpty(res) ? null : res;
|
2015-02-11 11:10:31 -08:00
|
|
|
}
|
2015-03-19 14:21:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
static group(c:modelModule.ControlGroup) {
|
|
|
|
var res = {};
|
|
|
|
StringMapWrapper.forEach(c.controls, (control, name) => {
|
|
|
|
if (c.contains(name) && isPresent(control.errors)) {
|
2015-03-25 10:51:05 -07:00
|
|
|
Validators._mergeErrors(control, res);
|
2015-03-19 14:21:40 -07:00
|
|
|
}
|
|
|
|
});
|
|
|
|
return StringMapWrapper.isEmpty(res) ? null : res;
|
|
|
|
}
|
2015-03-25 10:51:05 -07:00
|
|
|
|
|
|
|
static array(c:modelModule.ControlArray) {
|
|
|
|
var res = {};
|
|
|
|
ListWrapper.forEach(c.controls, (control) => {
|
|
|
|
if (isPresent(control.errors)) {
|
|
|
|
Validators._mergeErrors(control, res);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return StringMapWrapper.isEmpty(res) ? null : res;
|
|
|
|
}
|
|
|
|
|
|
|
|
static _mergeErrors(control, res) {
|
|
|
|
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
|
|
|
}
|