Search code examples
arraysvalidationreact-nativestatetextinput

how to set state (array) and validate multiple TextInputs added using a loop - react native


(new to react-native) I've added n number of TextInputs in a screen:

  1. Need to set state (array) for these TextInputs
  2. How to validate them to ensure that they are not empty, on a button press
renderFields(listNum) {    
    var numLists = parseInt(listNum, 10);    
    var fields = [];
    var numStr = "";
    for (let i = 0; i < numLists; i++) {
        numStr = JSON.stringify(i + 1);
        fields.push(
            <View key={i} style={styles.butInput}>
                <View style={styles.ChildViewStyle}>
                    <TextInput
                        ref={input => {
                          this.textInput = input;
                        }}
                        key={"txt_" + i}
                        style={styles.TextInputStyleClass}
                        textAlign={"left"}
                        editable={true}
                        maxLength={20}
                        defaultValue={numStr}
                    />
                </View>
            </View>
        );
    }
    return fields;
}

render() {
    const { navigation } = this.props;
    const listNum = navigation.getParam("listNum", 2);

    return (
        <View style={styles.container}>

            <View style={styles.InputContainer}>
                <ScrollView>{this.renderFields(listNum)}</ScrollView>
            </View>

            <View style={styles.settingRow}>
                <TouchableOpacity onPress={() => this.validateNum()}>
                    <Text style={styles.settingsBtnText}>S A V E</Text>
                </TouchableOpacity>
            </View>
        </View>
    );
}

Can't move further, please help


Solution

  • You can validate as follow:

    ref={o => (this["ref_" + i] = o)}

    validateNum() {
      var isValid = true;
      this.forms.some((i,index)=> {
                if (this["ref_"+index] && !!this["ref_"+index].text() ) {
                   isValid =false;
                }
            });
      return isValid;
    }
    

    To get text from TextInput create custom TextInput.