简体   繁体   English

如何在 React Native 中验证动态表单?

[英]How to validate dynamic form in React Native?

So, at first, i initialize empty state for required count ( if users gives input as 5 and submit i will be initialize the empty state with 5 state ),因此,首先,我为所需计数初始化空状态(如果用户将输入设为 5 并提交,我将使用 5 状态初始化空状态),

Then by using this, i am looping to create dynamic form ( am using map ), now how to validate the form !然后通过使用它,我正在循环创建动态表单(正在使用地图),现在如何验证表单!

My initial state formation :我的初始状态形成:

state = {usersDetails: []};

componentDidMount(){
    this.setInitialRow()
}

setInitialRows(){
        const seats = this.props.selectedSeats;
        let newRow = [];
        for(let i=0;i<seats.length;i+=1){
            newRow.push(
                {"seatName": seats[i].name,
                "passenger": [{
                    "name":"",
                    "gender": "",
                    }]
                })
        }
        this.setState({usersDetails: newRow})
    }

So from the above, i got my states and by using this am looping by this way:所以从上面,我得到了我的状态,并通过这种方式使用它循环:

 {this.state.usersDetails.map((s, i) =>{

             <TextInput 
                    style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
                    placeholder="Enter Name"
                    onChangeText={(text) => this.handleNameChange(text,i)}
             />

             <TextInput 
                    style={{ borderBottomWidth: 1, borderColor: '#f0eff4', height: 40 }}
                    placeholder="Enter Age"
                    onChangeText={(text) => this.handleAgeChange(text,i)}
             />
}

So , as per this i will be getting 5 pairs of above!所以,按照这个,我将得到 5 对以上! Now how to validate the input fields on each pair ?现在如何验证每对输入字段?

I tried this :我试过这个:

handleSubmit(){

        let row = this.state.usersDetails;

        function isNameEmpty(r){
            return r["passenger"][0].name === ''
        }
        function isAgeZero(r){
            return r["passenger"][0].age == 0
        }
       
        let isNameFail = row.find(isNameEmpty)
        let isAgeFail = row.find(isAgeZero)

        if(isNameFail || isAgeFail){
            // ToastAndroid.show('Please fill the Passenger Details',0.2)
        }else{
            console.log(row);
        }
    }

From this function, am getting toast warning !从这个功能,我收到吐司警告! But, how to display error message under the respective textInputs ?但是,如何在相应的 textInputs 下显示错误消息?

This might help just to have an idea of how this will be done这可能有助于了解如何做到这一点

class App extends Component {
  
  componentDidMount() {
    this.getDynamicInputs();
  }

  state = { userDetails: [], item_views: [], errorViews: [] };

  updateState = (index, value) => {
    const userDetails = [...this.state.userDetails]; //make a copy of array
    userDetails[index] = value;
    this.setState({ userDetails: userDetails });
  };

  getDynamicInputs() {
    const inputData = [];
    const errorViews = [];  
    for (let i = 0; i < count; i++) {
      inputData.push(
       <>
        <TextInput
          key={i}
          style={{ borderBottomWidth: 1, borderColor: "#f0eff4", height: 40 }}
          placeholder="Enter Name"
          onChangeText={(val) => this.updateState(i, val)}
          value={this.state.userDetails[i]}
        />
        { this.state.errorViews[i] && this.state.errorViews[i].error ? <Text>Required Field</Text> : null}
      </>
      );
      errorViews.push( { error: false } );
    }
    this.setState({ item_views: inputData, errorViews: errorViews });
  }

  validate(){

   const errorViews = _.clone(this.state.errorViews); 

   for (let i = 0; i < count; i++) {    
     if( this.state.userDetails[i] === “” ){
       errorViews[i].error = true;
     }
   }
   this.setState({errorViews});
  }

  render() {
    console.log(this.state.userDetails);
    return <View style={styles.app}>
            {this.state.item_views}
           <Button onPress={() => this.validate()}>Validate</Button>    
          </View>;
  }
}

const styles = StyleSheet.create({
  app: {
    flex: 1,
    backgroundColor: "pink"
  }
});

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM