首页 > 解决方案 > ReactJS 表单验证

问题描述

我对反应有简单的表单验证。我从这个来源制作的

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

有我的代码。当我提交表单时,isValid 函数内部发生输入错误。请帮我解决这个问题。

添加会员页面

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>
        );
    }

}

验证组件

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>
        );
    }

}

我不知道如何解决这个问题请帮助我...

标签: javascriptreactjsformsvalidationmaterial-ui

解决方案


谢谢大家。最后,我找到了解决方案。我像这样更改了句柄提交功能

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);
        }
    };

推荐阅读