NewOldMax / react-form-validator-core

Core validator component for react forms
MIT License
94 stars 44 forks source link

Extending validation logic. #20

Closed dasein108 closed 6 years ago

dasein108 commented 6 years ago

Hi. I've special validation case. Literally we should not allow to submit form if component marked as Claimed, while the value was not changed.

Next code, works fine, it's check if this field is claimed, marks it's as invalid and trigger related error msg. But it's works only visually, user can submit this form despite that was not changed=invalid.

I tried all possible ways to achieve this result and didn't get success. makeInvalid etc seems that not working, because this.validate() overwrite isValid state on form submit. Is it possible somehow extend/override validate() method to prevent from submit when it's not valid based on custom rule?

return class ClaimedValidator extends ValidatorComponent {
        constructor(props) {
            super(props)
            this.state = { ...this.state, changed: false, initialValue: ''}
        }   

        onChangeValue(value) {
            const {onChange} = this.props;
            onChange(value);
            if (!this.state.changed) {
                this.setState({initialValue: this.props.value})                 
            }
            this.setState({changed: true})                 
        }

        getHelperText() {
            const {isValid} = this.state;
            const {claimText, helperText} = this.props;

            if (isClaimError(this.props, this.state)) {
                return claimText;
            }
            else if (!isValid) {
                return this.getErrorMessage() || helperText;
            }
        }

        render() {
            /* eslint-disable no-unused-vars */
            const {
                onChange,
                errorMessages,
                validators,
                requiredError,
                helperText,
                validatorListener,
                withRequiredValidator,
                claimText,
                claims,
                ...rest
            } = this.props;

            const { isValid } = this.state;

            return (
                <WrappedComponent
                    {...rest}
                    error={!isValid || isClaimError(this.props, this.state)}
                    helperText={this.getHelperText()}
                    onChange={this.onChangeValue.bind(this)}
                />
            );
        }
    }
dasein108 commented 6 years ago

resolved by fork