Skip to content

Instantly share code, notes, and snippets.

@adamdickinson
Last active February 22, 2018 00:55
Show Gist options
  • Save adamdickinson/a11f3b67850d5e7282c20b3895691a3c to your computer and use it in GitHub Desktop.
Save adamdickinson/a11f3b67850d5e7282c20b3895691a3c to your computer and use it in GitHub Desktop.
import Button from "./Button"
import FieldContainer from "./FieldContainer"
import InputField from "./InputField"
import NumberField from "./NumberField"
import React from "react"
import { connect } from "react-redux"
export class CreateClient extends FieldContainer {
constructor() {
this.state = { client: {} }
this.rules = {
"client.name": { required: true },
"client.yearOfBirth": { min: 1989, max: 2018, step: 1, required: true }
}
}
render() {
const client = this.state.client
const errors = this.validator.validities
const connectField = this.connectField
return (
<InputField {...connectField("client.name")} />
<NumberField {...connectField("client.yearOfBirth")} />
<Button onClick={() => props.onCreateClient(this.state.client)} disabled={!this.validator.allValid}>Submit</Button>
)
}
}
export const mapDispatchToProps = dispatch => ({
onCreateClient: client => dispatch(clientActions.createClient(client))
})
export default connect(undefined, mapDispatchToProps)(CreateClient)
import React from "react"
import Validator from "./Validator.js"
export class FieldContainer extends React.Component {
constructor(props) {
super(props)
this.validator = new Validator
this.rules = {}
}
connectField(name) {
return {
onChange: event => this.onChange(name, event.target.value),
value: get(props, name),
error: get(this.validator.validities, name),
{...this.rules[name]}
}
}
onChange(name, value) {
this.setState(set({}, fieldName, value))
this.validator.check(name, value)
}
}
export default FieldContainer
export const email = value => /.+@.+/.test(value)
export const min = (value, limit) => isNaN(value) ? false : (value >= limit)
export const required = value => !!value
import * as validationRules from "validationRules"
export class Validator() {
constructor() {
this.validities = {}
this.allValid = true
}
check(name, value, rules) {
const result = this.validate(value, rules)
this.validities[name] = result
this.recheckValidity()
}
recheckValidity() {
this.allValid = !Object.values(this.validities).find(validity => validity.isValid == false)
}
remove(name) {
delete this.validities[name]
this.recheckValidity()
}
validate(value, rules) {
for( let (rule, limit) of Object.entries(rules) ) {
const result = (rule in validationRules) && validationRules[rule](value, limit)
if( result && !result.isValid ) return result
}
return { isValid: true }
}
}
export default Validator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment