useForm

Effortlessly manage and validate forms in Vue.js or Svelte with the useForm composition API function and built-in validation from "@tidy".

Streamline Form Management

The useForm composition API function from @tidy simplifies form management in your SPA applications. It provides a efficient way to define form state, integrate validation rules, handle form interactions, and access error messages. This streamlines form development, improves code organization, and enhances the developer experience.

Use Case: Login Form with Validation

Let's create a login page form with a single input element for the userName. We'll implement several validations and enable the submit button only when all validations pass. The validations include:

  1. Required field: The userName cannot be empty.
  2. Alphanumeric characters: The userName can only contain letters and numbers.
  3. Minimum length: The userName must be at least 6 characters long.
  4. Maximum length: The userName cannot exceed 10 characters.

Upon validation failure, the corresponding error message will be displayed.

Creating the Form Object with useForm

To create the form object, we use the useForm function and pass it an initial state object with the userName property set to an empty string.

import { useForm } from '@nattyjs/tidy';

const form = useForm({ userName: '' });

Binding Validators to the Form

Now, let's define the validation rules using the Validators option within useForm:

  const form = useForm({ userName: '' }, {
    validators: {
      userName: [
        Validators.required(),
        Validators.minLength({ value: 6 }),
        Validators.alphaNumeric(),
        Validators.maxLength({ value: 10 }),
      ],
    },
  });

Explanation of Validators:

  • Validators.required(): Ensures the userName field is not empty.
  • Validators.minLength({ value: 6 }): Sets a minimum length of 6 characters for the userName.
  • Validators.alphaNumeric(): Allows only letters and numbers in the userName.
  • Validators.maxLength({ value: 10 }): Sets a maximum length of 10 characters for the userName.

Building the Login Form Template

Here's the HTML template for the login form using Vue components:

<script setup lang="ts">
import { reactive } from 'vue';

import { useForm, Validators } from '@nattyjs/tidy';

const form = reactive(
useForm(
  { userName: '' },
  {
    validators: {
      userName: [
        Validators.required(),
        Validators.minLength({ value: 6 }),
        Validators.alphaNumeric(),
        Validators.maxLength({ value: 10 }),
      ],
    },
  }
)
);
</script>

<template>
<div>
  <label for="userName">User Name</label>
  <input type="text" id="username" v-model="form.userName" />
  <span>{{
    form.errorMessage.userName
  }}</span>
  <button :disabled="!form.valid">Submit</button>
</div>
</template>

Play online

You can start playing with this template in your browser using our online sandboxes: