javascript

Email Validation on Field Redux Form

You can pass your email validation regex function to validate attribute of redux form Field and it will check the email validation when you type any email.

import React from 'react'
import { Field, reduxForm } from 'redux-form'

const emailValidation = value =>
  value && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value) ?
  'Invalid email address' : undefined

const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type}/>
      {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
    </div>
  </div>
)

const EmailValidationForm = (props) => {
  const { handleSubmit, pristine, reset, submitting } = props
  return (
    <form onSubmit={handleSubmit}>
      <Field 
        name="email" 
        type="email"
        component={renderField}
        label="Email"
        validate={emailValidation}
      />
      <div>
        <button type="submit" disabled={submitting}>Submit</button>
        <button type="button" disabled={pristine || submitting} onClick={reset}>Reset</button>
      </div>
    </form>
  )
}

export default reduxForm({
  form: 'EmailValidationForm'
})(EmailValidationForm)

The code will show an error message while typing in the email field if you have entered the wrong email.

Was this helpful?