使用 Material UI 和 ReactJS 提交和验证表单
Form submit and validation with MaterialUI & ReactJS
我正在从 AntD 转移到 MaterialUI,并且不知道如何在不重新加载整个页面的情况下轻松实现表单验证和表单提交。
As an example,单击 "sign in" 后整个页面会重新加载,这对于 SPA 应用来说不是一个好主意。
我可以通过将 handleFunction 从元素移动到元素的 onClick 函数并从 Button 中删除 type="submit" 来绕过它,以免重新加载整个页面。这行得通,但它删除了验证,并且删除了用户单击 "Enter" 提交表单的能力。
知道如何实现吗?以下是我到目前为止可以使用但没有表单验证并且无法单击 'enter' 提交表单的内容:
return (
<Container component="main" maxWidth="xs">
<CssBaseline/>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon/>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form}>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
errorMessages={['this field is required', 'email is not valid']}
onInput={e => setEmail(e.target.value)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onInput={e => setPassword(e.target.value)}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary"/>}
label="Remember me"
/>
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onFinish}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link to={"/forgotpassword1"} variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link to={"/register"} variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Container>
);
你可以试试:
...
export default function SignIn() {
...
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [emailErrorText, setEmailErrorText] = React.useState("");
const [passwordErrorText, setPasswordErrorText] = React.useState("");
const onSubmit = e => {
e.preventDefault();
if (!email) {
setEmailErrorText("Please enter email");
} else {
setEmailErrorText("");
}
if (!password) {
setPasswordErrorText("Please enter password");
} else {
setPasswordErrorText("");
}
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
type="email"
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
value={email}
error={!!emailErrorText}
helperText={emailErrorText}
onChange={e => setEmail(e.target.value)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={password}
error={!!passwordErrorText}
helperText={passwordErrorText}
onChange={e => setPassword(e.target.value)}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onSubmit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
}
我们可以通过在 onSubmit 时添加 preventDefault 来实现。
处理提交:
const handleSubmit = e => {
e.preventDefault();
console.log("submit");
};
提交时:
<form className={classes.form} noValidate onSubmit={handleSubmit}>
检查 codesandbox
中的更新代码
从 'react' 注册卡片导入 React;
import { withRouter } from 'react-router-dom'
import { Grid, Paper, Avatar, TextField, Button } from '@material-ui/core'
class Register extends React.Component {
state = { username: "", password: "", confirmPassword: "", location: "", phonenumber: "", email: "" };
handleClickSignIn()
{
this.props.history.push("/Login");
}
validateEmail() {
console.log("Validate Email fun enter")
// var re = /\S+@\S+\.\S+/;
// return re.test(email);
if (this.state.email === "") {
alert("Plsease Enter Validate number");
}
}
validateNumber() {
if (this.state.phonenumber < 10) { alert("Please enter your phone number"); }
}
validateUsername() {
if (this.state.username === "") {
alert("Please Enter username");
return false
}
}
validatePassword() {
if (this.state.password < 6) { alert("Password must be at least 6 characters long."); }
}
validateLocation() {
if (this.state.location ==="") { alert("Please enter your location "); }
}
onSubmit() {
// this.validateUsername();
var un = this.validateUsername();
if (un ===false) {
return
}
// this.validatePassword();
// this.validateEmail();
// this.validateNumber();
// this.validateLocation();
console.log(this.state.username, this.state.password);
console.log(this.state.email);
console.log(this.state.confirmPassword);
console.log(this.state.location);
console.log(this.state.phonenumber);
}
render() {
const paperstyle = { padding: 30, height:'100', width: 350, margin: '20px auto' }
const avatarStyle = { backgroundColor: '#00adb5' }
const headerstyle = { margin: '10px 0' }
const btstyle = { margin: '10px 0' }
const ttstyle={margin:'5px 0'}
// const FormControlLabel = {fontSize:'5'}
return (
<Grid align='center' container
spacing={0}
direction="column"
alignItems="center"
justify="center"
style={{ minHeight: '100vh' }}>
<Paper elevation={10} style={paperstyle}>
<Avatar style={avatarStyle} > G</Avatar>
<h1 style={headerstyle}>GILGAL</h1>
<h2>Get Started Now</h2>
<TextField label='Name' fullWidth required style={ttstyle}
onChange={event => {
this.setState({username: event.target.value })
}}
/>
<TextField fullWidth label='Email ' style={ttstyle}
onChange={
event => {
this.setState
(
{
email: event.target.value
})
}} />
<TextField label='Password' type='password' fullWidth required style={ttstyle}
onChange={
event => { this.setState({ password: event.target.value }) }
}
/>
<TextField label='Confirm Password' type='password' fullWidth required style={ttstyle}
onChange={
event => { this.setState({ confirmPassword: event.target.value }) }
}
/>
<TextField label='Phonenumber' fullWidth required style={ttstyle}
onChange={
event => { this.setState({ phonenumber: event.target.value }) }
}
/>
<TextField label='Location' fullWidth style={ttstyle}
onChange={
event => { this.setState({ location: event.target.value }) }
}
/>
<input type="checkbox" id="agree" style={btstyle} /><label htmlFor="agree"> I agree to the website's <b>Privacy Policy & Terms and condition</b></label>
<Button type='submit' onClick={this.onSubmit.bind(this)} color='primary' variant="contained" fullWidth style={btstyle}>Register</Button>
<div><p > Already have an acount?
< a href onClick={this.handleClickSignIn.bind(this)} >Log in</a>
</p></div>
</Paper>
</Grid>
);
}
}
export default withRouter(Register)
我正在从 AntD 转移到 MaterialUI,并且不知道如何在不重新加载整个页面的情况下轻松实现表单验证和表单提交。
As an example,单击 "sign in" 后整个页面会重新加载,这对于 SPA 应用来说不是一个好主意。
我可以通过将 handleFunction 从元素移动到元素的 onClick 函数并从 Button 中删除 type="submit" 来绕过它,以免重新加载整个页面。这行得通,但它删除了验证,并且删除了用户单击 "Enter" 提交表单的能力。
知道如何实现吗?以下是我到目前为止可以使用但没有表单验证并且无法单击 'enter' 提交表单的内容:
return (
<Container component="main" maxWidth="xs">
<CssBaseline/>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon/>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form}>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
errorMessages={['this field is required', 'email is not valid']}
onInput={e => setEmail(e.target.value)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onInput={e => setPassword(e.target.value)}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary"/>}
label="Remember me"
/>
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onFinish}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link to={"/forgotpassword1"} variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link to={"/register"} variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Container>
);
你可以试试:
...
export default function SignIn() {
...
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [emailErrorText, setEmailErrorText] = React.useState("");
const [passwordErrorText, setPasswordErrorText] = React.useState("");
const onSubmit = e => {
e.preventDefault();
if (!email) {
setEmailErrorText("Please enter email");
} else {
setEmailErrorText("");
}
if (!password) {
setPasswordErrorText("Please enter password");
} else {
setPasswordErrorText("");
}
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
type="email"
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
value={email}
error={!!emailErrorText}
helperText={emailErrorText}
onChange={e => setEmail(e.target.value)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={password}
error={!!passwordErrorText}
helperText={passwordErrorText}
onChange={e => setPassword(e.target.value)}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={onSubmit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
}
我们可以通过在 onSubmit 时添加 preventDefault 来实现。
处理提交:
const handleSubmit = e => {
e.preventDefault();
console.log("submit");
};
提交时:
<form className={classes.form} noValidate onSubmit={handleSubmit}>
检查 codesandbox
中的更新代码从 'react' 注册卡片导入 React;
import { withRouter } from 'react-router-dom'
import { Grid, Paper, Avatar, TextField, Button } from '@material-ui/core'
class Register extends React.Component {
state = { username: "", password: "", confirmPassword: "", location: "", phonenumber: "", email: "" };
handleClickSignIn()
{
this.props.history.push("/Login");
}
validateEmail() {
console.log("Validate Email fun enter")
// var re = /\S+@\S+\.\S+/;
// return re.test(email);
if (this.state.email === "") {
alert("Plsease Enter Validate number");
}
}
validateNumber() {
if (this.state.phonenumber < 10) { alert("Please enter your phone number"); }
}
validateUsername() {
if (this.state.username === "") {
alert("Please Enter username");
return false
}
}
validatePassword() {
if (this.state.password < 6) { alert("Password must be at least 6 characters long."); }
}
validateLocation() {
if (this.state.location ==="") { alert("Please enter your location "); }
}
onSubmit() {
// this.validateUsername();
var un = this.validateUsername();
if (un ===false) {
return
}
// this.validatePassword();
// this.validateEmail();
// this.validateNumber();
// this.validateLocation();
console.log(this.state.username, this.state.password);
console.log(this.state.email);
console.log(this.state.confirmPassword);
console.log(this.state.location);
console.log(this.state.phonenumber);
}
render() {
const paperstyle = { padding: 30, height:'100', width: 350, margin: '20px auto' }
const avatarStyle = { backgroundColor: '#00adb5' }
const headerstyle = { margin: '10px 0' }
const btstyle = { margin: '10px 0' }
const ttstyle={margin:'5px 0'}
// const FormControlLabel = {fontSize:'5'}
return (
<Grid align='center' container
spacing={0}
direction="column"
alignItems="center"
justify="center"
style={{ minHeight: '100vh' }}>
<Paper elevation={10} style={paperstyle}>
<Avatar style={avatarStyle} > G</Avatar>
<h1 style={headerstyle}>GILGAL</h1>
<h2>Get Started Now</h2>
<TextField label='Name' fullWidth required style={ttstyle}
onChange={event => {
this.setState({username: event.target.value })
}}
/>
<TextField fullWidth label='Email ' style={ttstyle}
onChange={
event => {
this.setState
(
{
email: event.target.value
})
}} />
<TextField label='Password' type='password' fullWidth required style={ttstyle}
onChange={
event => { this.setState({ password: event.target.value }) }
}
/>
<TextField label='Confirm Password' type='password' fullWidth required style={ttstyle}
onChange={
event => { this.setState({ confirmPassword: event.target.value }) }
}
/>
<TextField label='Phonenumber' fullWidth required style={ttstyle}
onChange={
event => { this.setState({ phonenumber: event.target.value }) }
}
/>
<TextField label='Location' fullWidth style={ttstyle}
onChange={
event => { this.setState({ location: event.target.value }) }
}
/>
<input type="checkbox" id="agree" style={btstyle} /><label htmlFor="agree"> I agree to the website's <b>Privacy Policy & Terms and condition</b></label>
<Button type='submit' onClick={this.onSubmit.bind(this)} color='primary' variant="contained" fullWidth style={btstyle}>Register</Button>
<div><p > Already have an acount?
< a href onClick={this.handleClickSignIn.bind(this)} >Log in</a>
</p></div>
</Paper>
</Grid>
);
}
}
export default withRouter(Register)