mip*_*phe 4 validation react-native tcomb-form-native
如何confirmPassword使用tcomb-form-native库验证我的字段?
电子邮件和密码字段非常简单,我不知道如何比较模型中另一个字段的现有值.
这是我的代码.
const Email = t.refinement(t.String, (email) => {
const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
return reg.test(email);
});
const Password = t.refinement(t.String, (password) => {
const reg = /^(?=\S+$).{8,}$/;
return reg.test(password);
});
const RegistrationData = t.struct({
email: Email,
password: Password,
confirmPassword: t.String // Need some equality check
});
Run Code Online (Sandbox Code Playgroud)
我已经调查了文档https://github.com/gcanti/tcomb-form-native#disable-a-field-based-on-another-fields-value但我无法理解它.
这是我的解决方案:
首先,在类构造函数this.samePassword中定义将用于密码检查的类型.
this.samePassword = t.refinement(t.String, (s) => {
return s == this.state.person.user_password;
});
Run Code Online (Sandbox Code Playgroud)
比,this.samePassword在表单定义中使用类型
this.Person = t.struct({
user_id: t.String,
user_password: t.String,
reenter_password: this.samePassword,
});
Run Code Online (Sandbox Code Playgroud)
接下来,准备一个onChange函数来处理文本更改并保存到状态.
this.validate是一个变量,指示表单是否已输入.
onChange(person) {
this.setState({ person });
if(person.reenter_password != null && person.reenter_password != "") {
this.validate = this.refs.form.getValue();
}
}
Run Code Online (Sandbox Code Playgroud)
最后,钩this.state,this.onChange......上<Form>
<Form
ref="form"
type={this.Person}
value={this.state.person}
onChange={(v) => this.onChange(v)}
options={this.options}
/>
Run Code Online (Sandbox Code Playgroud)
完整代码是这样的:
import React from "react";
import {View, TouchableOpacity, Text} from "react-native";
import * as t from "tcomb-form-native";
let Form = t.form.Form;
export default class CreateUser extends React.Component {
constructor(props) {
super(props);
this.state = {
person: {}
};
this.samePassword = t.refinement(t.String, (s) => {
return s == this.state.person.user_password;
})
this.Person = t.struct({
user_id: t.String,
user_password: t.String,
reenter_password: this.samePassword,
});
this.options = {
fields: {
user_password: {
password: true,
secureTextEntry: true,
error: "",
},
reenter_password: {
password: true,
secureTextEntry: true,
error: "different password",
},
}
};
this.validate = null;
}
onChange(person) {
this.setState({ person });
if(person.reenter_password != null && person.reenter_password != "") {
this.validate = this.refs.form.getValue();
}
}
render() {
return (
<View>
<Form
ref="form"
type={this.Person}
value={this.state.person}
onChange={(v) => this.onChange(v)}
options={this.options}
/>
<View>
<TouchableOpacity
style={{backgroundColor: this.validate ? "blue": "red"}}
activeOpacity={this.validate ? 0.5 : 1}
disabled={this.validate? false: true}
onPress={() => this.doNext()}>
<Text> NEXT MOVE </Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
1958 次 |
| 最近记录: |