Search code examples
reactjssemantic-ui-reactformsy-react

Submit onBlur function only when the input is valid


I'm using input from formsy-semantic-ui-react for form validation and how can i run the onBlur function only when the field is valid?

There is a isValid() function in formsy-react, this.props.isValid() but how i call this function in the input from formsy-semantic-ui-react?

how i can do something like, onBlur={isValid() ? this.updateValue : null}?

<Form.Input
    instantValidation={false}
    name="input1"
    label="Input 1"
    validations="isNumeric"
    validationErrors={{
    isNumeric: "Enter numeric only"
    }}
    errorLabel={errorLabel}
    onBlur={this.updateValue}
/>

Solution

  • To get a behavior like this you'll have to create your own component that manages this. Using the withFormsy higher-order component you'll get access to the isValid function.

    This is just an example, but it should get you what you want

    import { withFormsy } from 'formsy-react';
    const MyInput = withFormsy(({ onValidUpdate, ...otherProps }) => {
        const onBlur = (event) => {
            if (otherProps.isValid()) {
                onValidUpdate()
            }
        }
    
        return (
            <Form.Input {...otherProps} onBlur={onBlur} />
        )
    })
    

    And then use the component like

    const onValidUpdate = () => console.log('this will only be called when valid')
    
    <MyInput
        name="email"
        label="Email"
        validations="isEmail"
        validationErrors={{ isEmail: 'Email not valid' }}
        errorLabel={errorLabel}
        onValidUpdate={onValidUpdate}
    />