How can I make a textField in react native required

Arnav Nath picture Arnav Nath · Aug 3, 2018 · Viewed 13.3k times · Source

I have a text field and a submit button but when I click on the submit button and haven't written anything inside of the Textfield it still proceeds the process so I want to make my text field a required text field but don't know how?

Answer

Aravind S picture Aravind S · Aug 3, 2018

Here is sandbox link with a demo https://codesandbox.io/s/lpx76zq6vm. When you click on the button, you can trigger a function to check whether your input field is empty

<Button
          onPress={() => {
            if (this.state.text.trim() === "") {
              this.setState(() => ({ nameError: "First name required." }));
            } else {
              this.setState(() => ({ nameError: null }));
            }
          }}
          title="Login"
  />

And your input field like

<TextInput
          style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
          onChangeText={text => this.setState({ text })}
          value={this.state.text}
        />
        {!!this.state.nameError && (
          <Text style={{ color: "red" }}>{this.state.nameError}</Text>
        )}