52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
var RibicaValidationMixin = {
|
|
_updateState: function(prop, value) {
|
|
var newState = {};
|
|
newState[prop] = value;
|
|
this.setState(newState);
|
|
},
|
|
_validate: function(prop, value) {
|
|
if(this.validations && this.validations[prop]) {
|
|
var cb = function(err) {
|
|
if (err !== undefined) {
|
|
var errors = this.state.errors;
|
|
if(err.length > 0) {
|
|
errors[prop] = err;
|
|
} else {
|
|
delete errors[prop];
|
|
}
|
|
this.setState({errors: errors});
|
|
}
|
|
}.bind(this);
|
|
|
|
var immediateErrors = this.validations[prop](value, cb);
|
|
if(immediateErrors !== undefined) {
|
|
cb(immediateErrors);
|
|
}
|
|
}
|
|
},
|
|
handleChange: function(prop) {
|
|
return function(event) {
|
|
event.preventDefault();
|
|
this._updateState(prop, event.target.value);
|
|
this._validate(prop, event.target.value);
|
|
}.bind(this);
|
|
|
|
},
|
|
getValidationMessages:function(prop) {
|
|
return (this.state.errors[prop] || []);
|
|
},
|
|
validate: function() {
|
|
for (var key in this.state) {
|
|
if (this.state.hasOwnProperty(key)) {
|
|
this._validate(key, this.state[key]);
|
|
}
|
|
}
|
|
return this.isValid();
|
|
},
|
|
isValid: function() {
|
|
return Object.keys(this.state.errors).length === 0;
|
|
}
|
|
};
|
|
|
|
module.exports = RibicaValidationMixin;
|