我有用于react的简单表单验证。我是从这个来源制作的
http://www.dotnetawesome.com/2016/02/create-simple-forms-with-validation-in-react-js.html
有我的代码。当我提交表单输入错误时,isValid函数内部发生错误。请帮助我解决此问题。
AddMember页面
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>
);
}
}
我不知道如何解决此问题,请帮助我...
答案 0 :(得分:1)
谢谢。终于,我找到了解决方案。我这样更改了句柄提交功能
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);
}
};
答案 1 :(得分:0)
问题出在on Submit上,因为输入未正确检索(我需要一个有效的代码,但似乎ref设置不正确),而在事件上,您将确切的引用传递给直接来自event的字段。检查您的裁判,一切应该正常。正如@SandipNirmal所说,Formik具有强大的验证功能,您可以在很大程度上复制它。