jquense / react-formal

Sophisticated HTML form management for React
http://jquense.github.io/react-formal
MIT License
526 stars 52 forks source link

Error message based on a yup objects' failed children requirements. #108

Open supermoos opened 7 years ago

supermoos commented 7 years ago

How would you set an error message for a structure like:

formModelSchema = yup.object({
        name: yup.object({
            first: yup.string().min(2).required('First name is required'),
            middle: yup.string(),
            last: yup.string().min(2).required('Last name is required')
        }).required('Full name is required'),
        email: yup.string().email().required('E-mail input is required')
    });
<Form onChange={this.onFormInputChange} onValidate={this.validateForm}
                      onInvalidSubmit={this.invalidFormHandler} debug={true}
                      delay={50}
                      schema={this.formModelSchema} defaultValue={this.state}
                      onSubmit={this.submitHandler}>
                        <FormGroup controlId="firstName" required>
                            <ControlLabel>First name</ControlLabel>
                            <Form.Field group="name" tagName={FormControl} name="name.first" alsoValidates={['name']} type="text"
                                        placeholder="Enter first name"/>
                        </FormGroup>
                        <FormGroup controlId="middleName">
                            <ControlLabel>Middle name</ControlLabel>
                            <Form.Field group="name" tagName={FormControl} name="name.middle" type="text"/>
                        </FormGroup>
                        <FormGroup controlId="lastName" required>
                            <ControlLabel>Last name</ControlLabel>
                            <Form.Field group="name" tagName={FormControl} name="name.last" alsoValidates={['name']} type="text"
                                        placeholder="Enter last name"/>
                        </FormGroup>
                        <Form.Message for={['name.first', 'name.last', 'name']}/>
</Form>

So that if for example first,name was input correctly but last.name was missing the error message would be: 'Full name is required'

rosskevin commented 7 years ago

@supermoos I'm not sure your code is written to meet your goal. As you wrote it, only an object instance is required. name: null would have to occur before you received Full name is required.

If you want Full name is required when either first or last name is missing, just add that to those fields.

formModelSchema = yup.object({
        name: yup.object({
            first: yup.string().min(2).required('Full name is required'),
            middle: yup.string(),
            last: yup.string().min(2).required('Full name is required')
        }),
        email: yup.string().email().required('E-mail input is required')
    });