Home > OS >  React: How to tell if Form is Valid/Invalid
React: How to tell if Form is Valid/Invalid

Time:08-29

How do I tell if a Form is Valid / Invalid in React?

Angular has this syntax on Formbuilders.

this.form.valid;

I am using this coding syntax. Curious if anything exists in the React library? Currently using Material UI Library.

Right now, I am doing if else statements and error checking all 10 fields. Looking for shorthand method.

https://onestepcode.com/creating-a-material-ui-form/

<form onSubmit={handleSubmit}>
      <Grid container alignItems="center" justify="center" direction="column">
        <Grid item>
          <TextField
            id="name-input"
            name="name"
            label="Name"
            type="text"
            value={formValues.name}
            onChange={handleInputChange}
          />
        </Grid>
        <Grid item>
          <TextField
            id="age-input"
            name="age"
            label="Age"
            type="number"
            value={formValues.age}
            onChange={handleInputChange}
          />

CodePudding user response:

I'd recommend using a library called Formik. It takes a bit of time to learn, but it's a really powerful library, and I use it all the time now (with MUI).

CodePudding user response:

As far as i understood your problem, you want to validate the form.

Which can be done by checking if the states are valid or not.

function handleSubmit(e){ 
e.preventDefault(); // to stop the form submission refresh the page

// now you can check the the validation part

// here are some sample validation that will check if the uername has 5 

// characters or not and checks if the age is greater than 18 or not.

// validations

if(formValues.name.length < 5 ) return; 
if(formValues.age < 18) return;

//if the code reaches this point then it is valid form 
sendToDb(); 
//similar more functions or statements can be called

}

By checking the state value in the submission of the form it can be validated.

The above mentioned way is the manual way but if you want to validate it using a single line validation by using some third party liberary, then this is the solution that i would likely go with.

I found this package in npmjs it works fine. This is how you can use it.

1. Install the package.

npm install react-native-input-validator

2. Usage:

import TextInput from "react-native-input-validator";

<TextInput type="email"  ref={someReference}/>

// check the value is valid or not in the submission of the form by using 

//[reference].isValid() method


someReference.isValid();

Hope it helps thank you.

for more reference check the package and see the use in more details in the examples.

package : https://www.npmjs.com/package/react-native-input-validator

  • Related