2015-02-11 11:10:31 -08:00
|
|
|
import {isPresent} from 'angular2/src/facade/lang';
|
|
|
|
import {StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
|
|
|
|
import {nullValidator, controlGroupValidator} from './validators';
|
|
|
|
|
|
|
|
export const VALID = "VALID";
|
|
|
|
export const INVALID = "INVALID";
|
2015-02-03 07:27:09 -08:00
|
|
|
|
|
|
|
export class Control {
|
|
|
|
value:any;
|
2015-02-11 11:10:31 -08:00
|
|
|
validator:Function;
|
|
|
|
status:string;
|
|
|
|
errors;
|
|
|
|
_parent:ControlGroup;
|
2015-02-03 07:27:09 -08:00
|
|
|
|
2015-02-11 11:10:31 -08:00
|
|
|
constructor(value:any, validator:Function = nullValidator) {
|
2015-02-03 07:27:09 -08:00
|
|
|
this.value = value;
|
2015-02-11 11:10:31 -08:00
|
|
|
this.validator = validator;
|
|
|
|
this._updateStatus();
|
|
|
|
}
|
|
|
|
|
|
|
|
updateValue(value:any) {
|
|
|
|
this.value = value;
|
|
|
|
this._updateStatus();
|
|
|
|
this._updateParent();
|
|
|
|
}
|
|
|
|
|
|
|
|
get valid() {
|
|
|
|
return this.status === VALID;
|
|
|
|
}
|
|
|
|
|
|
|
|
_updateStatus() {
|
|
|
|
this.errors = this.validator(this);
|
|
|
|
this.status = isPresent(this.errors) ? INVALID : VALID;
|
|
|
|
}
|
|
|
|
|
|
|
|
_updateParent() {
|
|
|
|
if (isPresent(this._parent)){
|
|
|
|
this._parent._controlChanged();
|
|
|
|
}
|
2015-02-03 07:27:09 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export class ControlGroup {
|
2015-02-11 11:10:31 -08:00
|
|
|
controls;
|
|
|
|
validator:Function;
|
|
|
|
status:string;
|
|
|
|
errors;
|
2015-02-03 07:27:09 -08:00
|
|
|
|
2015-02-11 11:10:31 -08:00
|
|
|
constructor(controls, validator:Function = controlGroupValidator) {
|
2015-02-03 07:27:09 -08:00
|
|
|
this.controls = controls;
|
2015-02-11 11:10:31 -08:00
|
|
|
this.validator = validator;
|
|
|
|
this._setParentForControls();
|
|
|
|
this._updateStatus();
|
2015-02-03 07:27:09 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
get value() {
|
|
|
|
var res = {};
|
|
|
|
StringMapWrapper.forEach(this.controls, (control, name) => {
|
|
|
|
res[name] = control.value;
|
|
|
|
});
|
|
|
|
return res;
|
|
|
|
}
|
2015-02-11 11:10:31 -08:00
|
|
|
|
|
|
|
get valid() {
|
|
|
|
return this.status === VALID;
|
|
|
|
}
|
|
|
|
|
|
|
|
_setParentForControls() {
|
|
|
|
StringMapWrapper.forEach(this.controls, (control, name) => {
|
|
|
|
control._parent = this;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
_updateStatus() {
|
|
|
|
this.errors = this.validator(this);
|
|
|
|
this.status = isPresent(this.errors) ? INVALID : VALID;
|
|
|
|
}
|
|
|
|
|
|
|
|
_controlChanged() {
|
|
|
|
this._updateStatus();
|
|
|
|
}
|
2015-02-03 07:27:09 -08:00
|
|
|
}
|