2017-07-17 52 views
0

这是做表单验证的最佳方法。我目前正在使用本机基础,我需要显示内联消息的用户名和密码。例如:“用户名是必需的”或“需要密码”React-Native表单验证

以下代码表示形式图。

import React, { Component } from 'react'; 
import { 
    Alert, 
    Text, 
    TextInput, 
    TouchableOpacity, 
    View, 
    AsyncStorage, 
    StyleSheet, 
    Image 
} from 'react-native'; 

import { Item, Label, Input } from 'native-base'; 

import { Actions } from 'react-native-router-flux'; 

export default class Login extends Component { 

    constructor() { 
    super(); 
    this.state = { 
     username: null, 
     password: null, 
     versionNumber:'N/A' }; 
    } 

    async saveItem(item, selectedValue) { 
    try { 
     await AsyncStorage.setItem(item, selectedValue); 
    } catch (error) { 
     console.error('AsyncStorage error: ' + error.message); 
    } 
    } 

    userLogin() { 
    if (!this.state.username || !this.state.password) return; 

    fetch('https://mobiletest.myapp.com/api/auth', { 
     method: 'POST', 
     headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, 
     body: JSON.stringify({ 
     username: this.state.username, 
     password: this.state.password 
     }) 
    }) 
     .then((response) => response.json()) 
     .then((responseData) => { 
     this.saveItem('id_token', responseData.userId); 
     Alert.alert('Login Success!'); 
     Actions.InspectionListGenerator(); 
     }) 
     .done(); 
    } 

    render() { 
    return (
     <BackgroundImage> 
     <View style={styles.container}> 
      <View> 
      <Image style={styles.logo} resizeMode='contain' source={require('../assets/images/logo.png')} /> 
      </View> 
      <Text style={styles.transformDataTitle}> Data</Text> 
      <Text style={styles.transformDataSubTitle}> Asset Management</Text> 
      <View style={styles.form}> 

      <Item floatingLabel style={StyleSheet.flatten(styles.floatingLabel)}> 
       <Label>Username</Label> 
       <Input 
         autoCapitalize="none" 
         onChangeText={(text) => this.setState({username: text})} 
         value={this.state.username} 
        /> 

      </Item> 

      <Item floatingLabel style={StyleSheet.flatten(styles.floatingLabel)}> 
       <Label>Password</Label> 
       <Input 
         onChangeText={(text) => this.setState({password: text})} 
         value={this.state.password} 
         secureTextEntry={true} 
        /> 

      </Item> 

      <TouchableOpacity style={styles.buttonWrapper} onPress={this.userLogin.bind(this)}> 
       <Text style={styles.buttonText}> LOGIN </Text> 
      </TouchableOpacity> 

      <Text style={styles.forgotYourPassword}>FORGOT YOUR PASSWORD?</Text> 

      <Text style={styles.versionNumber}>v N/A</Text> 
      </View> 
     </View> 
     </BackgroundImage> 
    ); 
    } 
} 

class BackgroundImage extends Component { 

    render() { 
    return (
     <Image source={require('../assets/images/login-bg.png')} 
     style={styles.backgroundImage}> 

     {this.props.children} 

     </Image> 
    ) 
    } 
} 

const styles = StyleSheet.create({ 
    backgroundImage: { 
    flex: 1, 
    width: null, 
    height: null, 
    resizeMode: 'cover' 
    }, 
    logo: { 
    flex: 1, 
    aspectRatio: 8, 
    resizeMode: 'contain' 
    }, 
    buttonText: { 
    fontSize: 16, 
    padding: 10, 
    textAlign: 'center', 
    color: '#ffffff' 
    }, 
    buttonWrapper: { 
    backgroundColor: '#054e6e', 
    marginBottom: 10, 
    marginTop: 10, 
    width: 300 
    }, 
    container: { 
    alignItems: 'center', 
    flex: 1, 
    justifyContent: 'center' 
    }, 
    form: { 
    width: 300, 
    marginTop: 20 
    }, 
    image: { 
    margin: 10 
    }, 
    floatingLabel:{ 
    backgroundColor: 'white' 
    }, 
    transformDataTitle: { 
    fontSize: 35, 
    margin: 10, 
    textAlign: 'center', 
    color: 'white', 
    fontFamily: "oxygen-regular" 
    }, 
    transformDataSubTitle: { 
    fontSize: 12, 
    textAlign: 'center', 
    color: 'white', 
    fontFamily: "oxygen-regular" 
    }, 
    forgotYourPassword:{ 
    marginTop: 20, 
    textAlign: 'center', 
    color: '#054e6e' 
    }, 
    versionNumber:{ 
    marginTop: 20, 
    textAlign: 'center', 
    color: 'white' 
    } 
}); 
+0

作为'redux'粉丝,我会推荐'redux-form'。我知道它需要一些'redux'的知识和一堆样板来设置,但它会让你的生活变得更加轻松。 – Alexander

回答

2

如果你不使用终极版,你可以添加两个PARAMATERS到你的国家,一个叫hasError这是一个布尔值,并告诉我们,如果有一个在形式和错误另一种称为的errorMessage包含错误信息以显示。

this.state = { 
     username: null, 
     password: null, 
     versionNumber:'N/A', 
     hasError: false, 
     errorMessage: '' 
}; 

然后当用户提交您需要检查每个输入,如果它的正确与否,如果不是你需要设置状态:hasError =真和的errorMessage =错误 的消息对于例如:

if(this.state.username.length<=3) 
    this.setState({hasError: true, errorMessage: "Username need to be longer than 3 characters"); 

,然后在表格的底部,您可以添加用红色文字,将显示错误文本,如果有任何,这样

{this.state.hasError ? <p>this.state.errorMessage</p> : null} 

当用户更改输入的内容时,不要忘记将其设置为false。

而且还除非this.state.hasError或者用于检查错误的任何变量设置为false,不发送HTTP请求。