Blog>
Snippets

Form Validation Techniques

Provide examples of synchronous and asynchronous form validation using TanStack Form in Solid.js, incorporating built-in validation methods and custom validation logic.
import { createForm } from '@tanstack/solid-form';
import { createEffect } from 'solid-js';

// Synchronous validation example
const { Form } = createForm({
  onSubmit: handleSubmit,
  validate(values) {
    const errors = {};
    if (!values.username) {
      errors.username = 'Username is required';
    }
    return errors;
  }
});

function MyForm() {
  return (
    <Form>
      {/* Form fields */}
      <button type="submit">Submit</button>
    </Form>
  );
}
This code sets up a form with TanStack Form in Solid.js, incorporating a synchronous validation to check if the username field is filled. If not, it returns an error message for that field.
import { createForm } from '@tanstack/solid-form';
import { createSignal } from 'solid-js';

// Asynchronous validation example
const { Form, useField } = createForm({
  onSubmit: handleSubmit,
  async validate(values) {
    const errors = {};
    if (values.username) {
      const isUsernameTaken = await checkUsername(values.username);
      if (isUsernameTaken) {
        errors.username = 'Username is already taken';
      }
    }
    return errors;
  }
});

async function checkUsername(username) {
  // Implement the logic to check username against a server-side resource
}

function MyForm() {
  return (
    <Form>
      {/* Form fields */}
      <button type="submit">Submit</button>
    </Form>
  );
}
This code snippet demonstrates how to implement asynchronous validation within a form using TanStack Form in Solid.js. It includes a custom async function (checkUsername) that would typically check the availability of a username against a server-side resource. If the username is taken, an error is returned.