Reputation: 489
I'm using material ui TextField in my react application. I need to know how to use error and helper text validation for my below code which carry email and password?. Please go through the code given below and provide me a suitable solution which i can pulloff
import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import swal from 'sweetalert';
class Login extends Component {
constructor(props){
super(props);
this.state={
email: '',
password: ''
}
}
async handleClick() {
const { email, password } = this.state;
let options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
}
let response = await fetch('/login', options);
response = await response.json();
if (!response) {
swal({
title: "Wrong Entry",
text: "Check your email and password",
icon: "warning",
button: "OK",
});
return;
}
if(response === 'user'){
await auth.userLogin();
this.props.history.push('/app/my');
return;
}
options = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
}
let res = await fetch('/team-check', options);
res = await res.json();
await auth.login();
if (!res) {
this.props.history.push('/choose-teams')
} else {
this.props.history.push('/dashboard',{state: { detail: response }})
}
}
render() {
return (
<div>
<MuiThemeProvider>
<div>
<AppBar
title="User-Login"
/>
<TextField
hintText="Enter your Email"
floatingLabelText="email"
onChange = {(event,newValue) => this.setState({email:newValue})}
/>
<br/>
<TextField
type="password"
hintText="Enter your Password"
floatingLabelText="Password"
onChange = {(event,newValue) => this.setState({password:newValue})}
/>
<br/>
<RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
</div>
<Link to="/forgot-password">Forgot-Password</Link>
</MuiThemeProvider>
</div>
);
}
}
const style = {
margin: 15,
};
export default Login;
I have try many answer from stack overflow, but its all are outdated now. Kindly go through my code and the help will be appreciated
Upvotes: 1
Views: 12702
Reputation: 13702
You can use error and helperText props and do the validation
TextField
<TextField
error={!!this.state.errors.email}
hintText="Enter your Email"
floatingLabelText="email"
onChange={(event, newValue) => this.setState({ email: newValue })}
helperText={this.state.errors.email && this.state.errors.email}
/>
handleSubmit:
async handleClick() {
const { email, password } = this.state;
if (email.length < 4) {
this.setState({
errors: { ...this.state.errors, email: "please enter valid email" }
});
}
...
Working demo is here
Note that you will need to add/reset errors by yourself. You can also consider to use validation libraries such as this . Also formik and yup is popular choice.
Upvotes: 1