Skip to content

Instantly share code, notes, and snippets.

@mkozhukharenko
Created October 11, 2016 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkozhukharenko/565ab2dc4928dd8a07c9c9e3e938319a to your computer and use it in GitHub Desktop.
Save mkozhukharenko/565ab2dc4928dd8a07c9c9e3e938319a to your computer and use it in GitHub Desktop.
React and MobX form validation - full example here https://github.com/mkozhukharenko/mobx-form-validation
// trun {fiels: {email: 'val', err:''}} to {email: 'val'}
var getValues = () => {
let data = {};
let form = toJS(this.form).fields;
Object.keys(form).map(key => {
data[key] = form[key].value
});
return data
}
import {action} from 'mobx'
var Validator = require('validatorjs');
class LoginFormStore {
validationRules = {
'email': 'required|email',
'password': 'required',
};
form = {
email: {
value: '',
error: ''
},
password: {
value: '',
error: ''
},
isValid: false
}
@action
onFieldChange = (field, value) => {
// update value and do a validation
this.form.fields[field].value = value; // set a new value
var validation = new Validator({
email: this.from.email.value,
password: this.from.email.value
}, this.validationRules);
this.form.meta.isValid = validation.passes(); // check if a form is valid
this.form.fields[field].error = validation.errors.first(field) // set an error if it exists
};
}
var loginFormModel = {
fields: {
email: {
value: '', // binds to input value
error: null, // shows beneif the input
},
password: {
value: '',
error: null,
},
},
meta: {
isValid: true, // is a 'submit' value disabled?
error: null, // some generic error
},
}
var onFieldChange = (field, value) => {
this.form.fields[field].value = value; // set a new value
var validation = new Validator(this.getValues(), this.validationRules);
this.form.meta.isValid = validation.passes(); // check if a form is valid
this.form.fields[field].error = validation.errors.first(field) // set an error if it exist
};
var data = {
name: 'John',
email: 'not-valid-email'
};
var rules = {
name: 'required',
email: 'required|email'
};
var validation = new Validator(data, rules);
validation.passes(); // false
validation.errors.first('email'); // 'The email format is invalid.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment