1

I have simple form validation for react. I made this from this source

http://www.dotnetawesome.com/2016/02/create-simple-forms-with-validation-in-react-js.html

there is my code. when I submit the form input error occurred inside of the isValid function. please help me to fix this.

AddMember page

class AddMember extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading : true,
            formData: {
                fname   : "",
                lname   : "",
                address1: "",
                address2: "",
                city    : "",
                mobile  : "",
                role    : "",
                email   : "",
                gender  : ""
            },
            fields  : []
        };

        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.register = this.register.bind(this);
    }

    componentDidMount() {
        document.title = globals.title + "Add New Member";
        setTimeout(() => {
            this.setState({loading: false})
        }, 500);
    }


    handleSubmit = (e) => {
        e.preventDefault();

        let validForm = true;
        this.state.fields.forEach(function (field) {
            console.log(field.refs[field.props.name]);
            if (typeof field.isValid === "function") {
                let validField = field.isValid(field.refs[field.props.name]);
                validForm = validForm && validField
            }
        });

        if (validForm) {
            console.log(this.state.fields);
        }
    };

    handleChange = (name) => (value) => {
        let formData = {
            [name]: value
        };
        this.setState({
            formData: formData
        })
    };

    register (field)  {
        let s = this.state.fields;
        s.push(field);
        this.setState({fields: s});
        console.log("ss");
    };

    render() {
        const {classes} = this.props;

        if (this.state.loading) {
            return (
                <div className={classes.posRelative}>
                    <CircularProgress size={80} className={classes.progress}/>
                </div>
            )
        }

        return (
            <Grow in={true} style={{transformOrigin: "0 0 0"}}>
                <Paper className={classes.root}>
                    <form
                        onSubmit={this.handleSubmit}
                        noValidate>

                        <Grid container spacing={16}>
                            <Grid item xs={12} sm={6}>
                                <MuiValidator placeholder={"First Name"} name={"fname"} type={"email"}
                                              onChange={this.handleChange("fname")} value={this.state.formData.fname}
                                              inputProps={{required:true}} onComponentMounted={this.register} fullWidth={true}/>
                            </Grid>

                        </Grid>
                        <Button type={"submit"} variant={"raised"} color={"primary"}>Submit</Button>
                    </form>
                </Paper>
            </Grow>
        );
    }

}

validation component

class MuiValidator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error   : "",
            errorMsg: ""
        };
        this.isValid = this.isValid.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange (e) {
        this.props.onChange(e.target.value);
        let isValidField = this.isValid(e.target);
        // console.log(e.target.appendChild());
        console.log(isValidField);

    };

    //Validation function
    isValid (input) {
        console.log(input);
        //check required field
        if (input.getAttribute("required") !== null && input.value === "") {
            this.setState({error: true,errorMsg:'This field is required'});
            return false
        } else {
            this.setState({error: false,errorMsg:''});
            // input.nextSibling.textContent = "";
        }
        if (input.getAttribute("type") === "email" && input.value !== "") {
            if (!this.validateEmail(input.value)) {
                this.setState({error: true, errorMsg: "Please enter valid email address"})
                return false
            } else {
                this.setState({error: false,errorMsg:''});
            }
        }
        return true;
    };

    validateEmail = (value) => {
        let re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(value);
    };

    componentDidMount() {
        if (this.props.onComponentMounted) {
            this.props.onComponentMounted(this);
        }
    }


    render() {
        const {error,errorMsg} = this.state;
        return (
            <div>
                <FormControl fullWidth={this.props.fullWidth} margin={"normal"} error={!!error}>
                    <InputLabel>First Name</InputLabel>
                    <Input name={this.props.name} type={this.props.type} placeholder={this.props.placeholder}
                           value={this.props.value} onChange={this.handleChange}
                           inputProps={this.props.inputProps} ref={this.props.name}/>
                    {error && <FormHelperText>{errorMsg}</FormHelperText>}
                </FormControl>
            </div>
        );
    }

}

I have no idea how can fix this please help me...

6
  • what's the error in console ? Commented Jul 30, 2018 at 15:57
  • TypeError: input.getAttribute is not a function this is the error in console Commented Jul 30, 2018 at 16:06
  • this happens when typing or when submitting, or both ? Commented Jul 30, 2018 at 16:10
  • when the form submit. typing is already working no errors Commented Jul 30, 2018 at 16:24
  • 1
    It’s okay to handle validations manually if we have small form operations. But in case your dealing with large forms use formik it has great form validation support for react. Commented Jul 30, 2018 at 16:25

2 Answers 2

1

thanks all. finally, I found a solution. I changed the handle submit function like this

handleSubmit = (e) => {
        e.preventDefault();

        let validForm = true;
        this.state.fields.forEach((field) => {
            //create input element
            let elm = document.createElement("input");
            for (let attr in field.refs[field.props.name].props) {
                if (attr !== "onChange" && attr !== "inputProps") {
                    elm.setAttribute(attr, field.refs[field.props.name].props[attr]);
                    elm.removeAttribute("onChange");
                }
                if (attr === "inputProps") {
                    for (let props in field.refs[field.props.name].props.inputProps) {
                        elm.setAttribute(props, field.refs[field.props.name].props.inputProps[props]);
                    }
                }
            }


            if (typeof field.isValid === "function") {
                let validField = field.isValid(elm);
                validForm = validForm && validField
            }
        });

        if (validForm) {
            console.log(this.state.fields);
        }
    };
Sign up to request clarification or add additional context in comments.

Comments

0

The problem resides in the on submit because the input is not retrieved correctly (I need a working code but it seems refs are not set correctly) while on event you pass the exact reference to the field coming directly from event. Check your refs and everything should work ok. As said from @SandipNirmal Formik has a great validation feature that you are substantially replicating.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.