1

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}
          />

3 Answers 3

5

To tell if a form content is valid or not - regardless the framework - you can simply use the following:

  const handleSubmit = (e) => {
    e.preventDefault();

    const formElement = e.target;
    const isValid = formElement.checkValidity();
    
    // add more logic here
  }

...

    <form
      action={action}
      onSubmit={handleSubmit}
      className={style.form}
    >
      <input type='email' name='email' />
      <input type='number' name='age' required />
    </form>

This will use the built-in validation function and will return true if the email is correct and the age is provided.

Please note that email is not 'required', i.e. an empty value is considered correct.

I just wrote an article where I discuss exactly this: form validation/submission using built-in validation API. No need to install any package!

https://medium.com/p/491327f985d0

Sign up to request clarification or add additional context in comments.

1 Comment

This is very clean and cool solution. I have not used it for very complex types of form but for simple forms where the required or error props are in, it works nice. Thank you.
2

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

4 Comments

is there anything in the native react library however? will take a look then, thanks
react doesn't usually build in features like that itself, it's just the core functionality.
ok, please add last comment into answer, thanks !
also, feel free to upvote question, thanks
1

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 username 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 library, 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

2 Comments

yeah, was hoping there a single line check, instead of doing if-then for all 10 of my form fields
@mattsmith5 check out the new edit i hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.