Answer the question
In order to leave comments, you need to log in
How to validate a select field?
I created a form with react-forms and am trying to validate its fields. There are no problems with fields of type input and textarea, but it is not possible to validate a field of type select. Please help me to do this.
Specifically, the problem is that if the user fills in all fields except select, then the form is still sent, as can be seen from the completed function onSubmit
.
Here are the validation rules:
export const required = value => value ? undefined : 'Required';
export const maxLength = max => value =>
value && value.length > max ? `Must be ${max} characters or less` : undefined;
export const maxLength15 = maxLength(15);
import React from 'react';
import { Field, reduxForm, reset } from 'redux-form';
import store from '../../redux/store';
import { required, maxLength15 } from '../../Validation/index';
const renderField = typeEl => ({ input, label, type, meta: { touched, error, warning } }) => (
<div>
<label>{label} -- {typeEl}</label>
<div>
{ typeEl === 'textarea' && <textarea {...input} placeholder={label} type={type}></textarea> }
{ typeEl === 'input' && <input {...input} placeholder={label} type={type}/> }
{ typeEl === 'select' && <select {...input}><option></option><option value="Male">Male</option><option value="Female">Female</option></select> }
{touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
</div>
</div>
)
function MessageForm(props) {
const { handleSubmit, reset, submitting } = props;
return (
<form onSubmit={ handleSubmit }>
<Field
name="name"
component={ renderField('input') }
type="text"
label="name"
validate={[ required, maxLength15 ]}
/>
<br/>
<Field
name="subject"
component={ renderField('input') }
type="text"
label="subject"
validate={[ required, maxLength15 ]}
/>
<br/>
<Field
name="gender"
component={ renderField('select') }
label="gender"
/>
<br/>
<Field
name="text"
component={ renderField('textarea') }
placeholder="text"
validate={[ required ]}
/>
<br/>
<button type="submit" disabled={ submitting }>Submit</button>
</form>
);
}
const MessageReduxForm = reduxForm({
form: 'message',
})(MessageForm)
function MessageReduxFormWrap() {
function onSubmit(formData) {
store.dispatch(reset('message'));
console.log('submitted', formData);
}
return <MessageReduxForm onSubmit={ onSubmit }/>
}
export default MessageReduxFormWrap;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question