Unlock React Form Validation with Trivule: The Game-Changing Approach
Tags: react, javascript, frontend
Published: 2024-05-28 00:27:33

If you love the simplicity of React, you'll adore [Trivule](https://github.com/trivule/trivule). This solution allows you to validate your forms easily and effectively. In this article, we will validate a form with two fields: email and message, to show how user-friendly and straightforward it is to use Trivule.

## Example of output
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4ir8ynignoofq7s1isz.jpeg)
[Extract from](https://github.com/devalade/trivule-react)
## Creating the Project
To start, create a project with Vite:

```bash
npm create vite@latest
```
Follow the instructions to complete the setup. I chose the TypeScript option, but you can choose whichever suits you best.

Then, install Trivule:

```bash
npm install trivule
```

### Validation Rules
- **Email**: required, maximum 63 characters, must be a Gmail address.
- **Message**: required, maximum 250 characters, must start with "Hello".

## Creating the React Component
Create a file `form.tsx` in your React working directory:

```jsx
import React, { useEffect, SyntheticEvent } from "react";
import { TrivuleForm } from "trivule";

// Callback to define validation rules
const bindRules = (trivuleForm: TrivuleForm) => {
  trivuleForm.make({
    email: {
      rules: "required|email|endWith:@gmail.com|max:63",
      messages: {
        endWith: "Only Gmail addresses are allowed",
      },
    },
    message: {
      rules: "required|startWith:Hello|max:250",
    },
  });
};

// React Component
function Form() {
  const trivuleForm = new TrivuleForm({ invalidClass: "is-invalid" });
  trivuleForm.afterBinding(bindRules);

  useEffect(() => {
    // The code runs once the form is found in the DOM
    trivuleForm.bind("#myForm");
  }, []);

  const handleSubmit = (e: SyntheticEvent) => {
    if (!trivuleForm.passes()) {
      e.preventDefault();
      return;
    }
    const data = trivuleForm.validated();
    console.log(data);
  };

  return (
    <form id="myForm" onSubmit={handleSubmit}>
      <h3>Trivule + React-vite</h3>
      <div className="form-group">
        <input type="text" name="email" />
        <div className="alert alert-danger" role="alert">
          <div data-tr-feedback="email"></div>
        </div>
      </div>
      <div className="form-group">
        <textarea name="message"></textarea>
        <div className="alert alert-danger" role="alert">
          <div data-tr-feedback="message"></div>
        </div>
      </div>
      <button type="submit">Submit</button>
    </form>
  );
}

export default Form;
```

### Integrating into the Application
Import and use the `Form` component in `App.tsx`:

```jsx
import React from "react";
import "./App.css";
import Form from "./form";

function App() {
  return <Form />;
}

export default App;
```
## Styling Flexibility
Trivule is agnostic about the styling of your form. It provides an API that allows you to apply your own styles based on the validation status. You can define classes to indicate valid or invalid states, and Trivule will handle the rest.

### Learn More
To further your knowledge of Trivule, check out the following resources:
- [Quick start tutorial | Trivule](https://www.trivule.com/docs/tuto)
- [Validation Rules](https://www.trivule.com/docs/rules)
- [Messages | Trivule](https://www.trivule.com/docs/messages)
- [Events | Trivule](https://www.trivule.com/docs/events)

You can also create a TrivuleForm component, export it, and validate your forms without manual initialization. Check out an example on [GitHub](https://github.com/devalade/trivule-react).