Skip to content

Instantly share code, notes, and snippets.

@shinaisan
Last active October 26, 2017 13:48
Show Gist options
  • Save shinaisan/a04049ce7ea561713f372269f14c43fb to your computer and use it in GitHub Desktop.
Save shinaisan/a04049ce7ea561713f372269f14c43fb to your computer and use it in GitHub Desktop.
Redux Form - Field-Level Validation Example
import React from 'react';
import FieldLevelValidationForm from './FieldLevelValidationForm';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from './reducers';
import "bootstrap/dist/css/bootstrap.css";
const store = createStore(reducer);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.setState({debug: ''});
}
submit(values) {
this.setState({debug: JSON.stringify(values)});
}
render() {
const submit = this.submit.bind(this);
return (
<Provider store={store}>
<div>
<FieldLevelValidationForm onSubmit={submit} />
<div>
<pre>{this.state.debug}</pre>
</div>
</div>
</Provider>
);
}
}
export default App;
#!/bin/bash
NAME=redux-form-field-level-validation
echo -n "This script runs create-react-app $NAME. Proceed? (Y/N) "
read YN
if [ x$YN != xY ]
then
echo "Bye."
exit
fi
# Delete this line only if you are sure what is done from this line on.
exit
create-react-app $NAME
cd $NAME
cp -v ../package.json .
cd src
rm -f App.* logo.svg
cp -v ../../*.js .
cd ..
yarn install
echo 'To launch the dev server, run `yarn run start`.'
import React from 'react'
import { Field, reduxForm } from 'redux-form'
import {
Form, FormGroup,
Row, Col,
Button
} from 'react-bootstrap';
const required = value => (value ? undefined : 'Required')
const maxLength = max => value =>
value && value.length > max ? `Must be ${max} characters or less` : undefined
const maxLength15 = maxLength(15)
export const minLength = min => value =>
value && value.length < min ? `Must be ${min} characters or more` : undefined
export const minLength2 = minLength(2)
const number = value =>
value && isNaN(Number(value)) ? 'Must be a number' : undefined
const minValue = min => value =>
value && value < min ? `Must be at least ${min}` : undefined
const minValue18 = minValue(18)
const email = value =>
value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)
? 'Invalid email address'
: undefined
const tooOld = value =>
value && value > 65 ? 'You might be too old for this' : undefined
const aol = value =>
value && /.+@aol\.com/.test(value)
? 'Really? You still use AOL for your email?'
: undefined
const alphaNumeric = value =>
value && /[^a-zA-Z0-9 ]/i.test(value)
? 'Only alphanumeric characters'
: undefined
export const phoneNumber = value =>
value && !/^(0|[1-9][0-9]{9})$/i.test(value)
? 'Invalid phone number, must be 10 digits'
: undefined
const renderField = ({
input,
label,
type,
meta: { touched, error, warning }
}) => (
<FormGroup>
<Row>
<Col sm={2}>
<label>{label}</label>
</Col>
<Col sm={8}>
<input {...input} placeholder={label} type={type} size="48" />
{
touched &&
((error && <span>{error}</span>) ||
(warning && <span>{warning}</span>))
}
</Col>
</Row>
</FormGroup>
)
const FieldLevelValidationForm = props => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<Form onSubmit={handleSubmit}>
<Field
name="username"
type="text"
component={renderField}
label="Username"
validate={[required, maxLength15, minLength2]}
warn={alphaNumeric}
/>
<Field
name="email"
type="email"
component={renderField}
label="Email"
validate={email}
warn={aol}
/>
<Field
name="age"
type="number"
component={renderField}
label="Age"
validate={[required, number, minValue18]}
warn={tooOld}
/>
<Field
name="phone"
type="number"
component={renderField}
label="Phone number"
validate={[required, phoneNumber]}
/>
<div>
<Button type="submit" bsStyle="primary"
disabled={submitting}>
Submit
</Button>
<Button type="button" bsStyle="default"
disabled={pristine || submitting} onClick={reset}>
Clear Values
</Button>
</div>
</Form>
)
}
export default reduxForm({
form: 'fieldLevelValidation' // a unique identifier for this form
})(FieldLevelValidationForm)
{
"name": "redux-form-field-level-validation",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^3.3.7",
"react": "^16.0.0",
"react-bootstrap": "^0.31.5",
"react-dom": "^16.0.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2",
"redux-form": "^7.1.2"
},
"devDependencies": {
"react-scripts": "1.0.14"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
const rootReducer = combineReducers({
// ...your other reducers here
// you have to pass formReducer under 'form' key,
// for custom keys look up the docs for 'getFormState'
form: formReducer
});
export default rootReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment