我有一个基本的登录表单,我已经使用实质性UI实施了表单验证。
即使文本框中有一个值,验证也是可见的。
代码:
LoginComponent
import React from "react";
import TextField from "material-ui/TextField";
import RaisedButton from "material-ui/RaisedButton";
export class loginComponent extends React.Component {
constructor() {
super();
this.state = {
username: "",
usernameError: "",
password: "",
passwordError:""
};
};
onChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
validate = () => {
let isError = false;
const errors = {
usernameError: "",
passwordError: ""
};
if (this.state.username.trim.length === 0) {
isError = true;
errors.usernameError = "Username is required";
}
if (this.state.password.trim.length === 0) {
isError = true;
errors.passwordError = "password is required";
}
this.setState({
...this.state,
...errors
});
return isError;
}
onSubmit = e => {
e.preventDefault();
const error = this.validate();
if (!error) {
console.log(this.state);
}
};
render() {
return (
<div className="container">
<div id="loginbox" style={{ marginTop: 50 }} className="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div className="panel panel-info">
<div className="panel-heading">
<div className="panel-title">Sign In</div>
</div>
<div style={{ paddingTop: 30 }} className="panel-body">
<form id="loginform" className="form-horizontal" role="form">
<div style={{ marginBottom: 25 }} className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-user"></i></span>
<TextField
name="username"
floatingLabelText="User name"
value={this.state.username}
onChange={e => this.onChange(e)}
errorText={this.state.usernameError}
floatingLabelFixed
/>
</div>
<div style={{ marginBottom: 25 }} className="input-group">
<span className="input-group-addon"><i className="glyphicon glyphicon-lock"></i></span>
<TextField type="password"
name="password"
value={this.state.password}
floatingLabelText="password"
onChange={e => this.onChange(e)}
errorText={this.state.passwordError}
floatingLabelFixed
/>
</div>
<div style={{ paddingTop: 10 }} className="form-group">
<div className="col-sm-12 controls">
<RaisedButton label="Login" onClick={e => this.onSubmit(e)} primary />
</div>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
这是基本的必需长度验证,即使在文本框中输入值后仍会被触发,有人可以建议我做错了吗。
答案 0 :(得分:0)
我想与您进行比较:
this.state.password.trim.length
在计算return 0
的长度时将始终为password.trim
。
使用this.state.password.trim().length
将修剪passowrd
的值并返回其长度。