redux form make field required

Solutions on MaxInterview for redux form make field required by the best coders in the world

showing results for - "redux form make field required"
Aaliyah
02 Mar 2019
1import React from 'react'
2import { Field, reduxForm } from 'redux-form'
3
4const required = value => value ? undefined : 'Required'
5const maxLength = max => value =>
6  value && value.length > max ? `Must be ${max} characters or less` : undefined
7const maxLength15 = maxLength(15)
8const number = value => value && isNaN(Number(value)) ? 'Must be a number' : undefined
9const minValue = min => value =>
10  value && value < min ? `Must be at least ${min}` : undefined
11const minValue18 = minValue(18)
12const email = value =>
13  value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ?
14  'Invalid email address' : undefined
15const tooOld = value =>
16  value && value > 65 ? 'You might be too old for this' : undefined
17const aol = value =>
18  value && /.+@aol\.com/.test(value) ?
19  'Really? You still use AOL for your email?' : undefined
20
21const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
22  <div>
23    <label>{label}</label>
24    <div>
25      <input {...input} placeholder={label} type={type}/>
26      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
27    </div>
28  </div>
29)
30
31const FieldLevelValidationForm = (props) => {
32  const { handleSubmit, pristine, reset, submitting } = props
33  return (
34    <form onSubmit={handleSubmit}>
35      <Field name="username" type="text"
36        component={renderField} label="Username"
37        validate={[ required, maxLength15 ]}
38      />
39      <Field name="email" type="email"
40        component={renderField} label="Email"
41        validate={email}
42        warn={aol}
43      />
44      <Field name="age" type="number"
45        component={renderField} label="Age"
46        validate={[ required, number, minValue18 ]}
47        warn={tooOld}
48      />
49      <div>
50        <button type="submit" disabled={submitting}>Submit</button>
51        <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
52      </div>
53    </form>
54  )
55}
56
57export default reduxForm({
58  form: 'fieldLevelValidation' // a unique identifier for this form
59})(FieldLevelValidationForm)
60