Reputation: 13689
Im using reduxForm 7.4.2 , working with client side validation on simple form.
The form is being submitted on page load and shows error like below :
I want to prevent form being submitted on page load and show errors only when users click Submit button
Here is the form component using reduxForm :
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const renderField = ({ input, label, type, meta: { touched, error, warning } }) => {
console.log(error);
return(
<div className="form-group">
<label>{label}</label>
<input {...input} placeholder={label} type={type} className="form-control" />
{error && <div className="invalid-feedback d-block">{error}</div>}
</div>
)
}
const validate = values => {
const errors = {}
if (!values.name) {
errors.name = 'Name is Required'
} else if (values.name.length < 2) {
errors.name = 'Must be 2 characters or more'
}
if (!values.email) {
errors.email = 'Email is Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
}
if (!values.password) {
errors.password = 'Password Required'
} else if (values.password.length < 6) {
errors.password = 'Password must be 6 characters'
}
return errors
}
const Form1Child=(props)=>{
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit} className="needs-validation" noValidate>
<Field name="name" type="text" component={renderField} label="Name"/>
<Field name="email" type="email" component={renderField} label="Email"/>
<Field name="password" type="password" component={renderField} label="Password"/>
<div>
<button className="btn btn-primary" type="submit" disabled={submitting}>Submit</button>
<button className="btn btn-default" type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
export default reduxForm({
form: 'form1',
validate
})(Form1Child)
Here is the parent component :
import React, { Component } from 'react'
import Form1Child from './Form1Child';
class Form1 extends Component {
constructor(){
super();
this.state={
}
}
handleSubmit=values=>{
alert(JSON.stringify(values));
}
render() {
return (
<Form1Child onSubmit={this.handleSubmit}/>
)
}
}
export default Form1;
Upvotes: 3
Views: 1881
Reputation: 81
Its happen because you have not checked field is dirty or not.
In your renderField
component you haven't checked field is touched or not.
In your renderField
component replace this line
{error && <div className="invalid-feedback d-block">{error}</div>}
with
{touched && error && <div className="invalid-feedback d-block">{error}</div>}
and it should work.
Upvotes: 0
Reputation: 1368
In your validate function, do the following:
throw new SubmissionError('There were errors.')
This will prevent the action
@@redux-form/SET_SUBMIT_SUCCEEDED
Upvotes: 0