javascript 如果有人触摸输入框并将其留空(已修改),我如何使用 React Native 验证输入文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48821403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i Validate inputext with react native if someone touch input box and leave it blank(Modified)
提问by Manoj Bhardwaj
回答by Vishu Bhardwaj
There are 2 types of validation. 1, when you press some button to login and 2 when you validate text input every time someone presses a character. You need to save a state for the validation error message.
有两种类型的验证。1,当您按下某个按钮登录时 2 当您每次有人按下一个字符时验证文本输入时。您需要保存验证错误消息的状态。
<Button onPress={() => {
if (this.state.text.trim() === "") {
this.setState(() => ({ nameError: "First name required."}));
} else {
this.setState(() => ({ nameError: null}));
}
}} title="Login">
Now where you display text input, below it you need to show a text which is displayed when the nameErrorproperty in state is not null,
现在显示文本输入的地方,在它下面你需要显示一个文本,当nameErrorstate 中的属性不为空时,
<TextInput style={...} onChangeText={...} value={...} />
{!!this.state.nameError && (
<Text style={{color: 'red'}}>
{this.state.nameError}
</Text>
)}


