Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a textField in react native required

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?

like image 953
Arnav Nath Avatar asked Aug 03 '18 04:08

Arnav Nath


People also ask

How do I make text not editable in react native?

You can make the TextBox as read-only by setting the readonly attribute to the input element.

How do you validate TextInput values in react native?

You can validate your input value using onBlur event on TextInput You can apply your regex or check conditions on this event.

What is TextInput in react native?

TextInput is a Core Component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.


1 Answers

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>
        )}
like image 193
Aravind S Avatar answered Sep 21 '22 08:09

Aravind S