简体   繁体   中英

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 ),

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! 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 ?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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