Validate Form on Submit

This page explains how to validate a form when the submit button is clicked using @tidy. Here, validation occurs only when the user attempts to submit the form, ensuring a smoother user experience.

Configuration for On-Submit Validation

In your application's root file, you'll configure @nattyjs/tidy to run validation specifically on submit:

import { configure, Validators, RunValidatorStrategy } from "@nattyjs/tidy";

configure({
  runValidatorStrategy: RunValidatorStrategy.OnSubmit,
  errorMessage: {
    validator: {
      required: 'this field is required.', // Customize error messages as needed
    }
  }
});
  • RunValidatorStrategy.OnSubmit: This setting ensures validators are triggered only when the form is submitted.
  • errorMessage: This object allows you to customize error messages displayed to the user. Here, we've defined a message for the required validator.

Creating the Form with Validation

Here's how you create the userForm object with a validation rule for the name field

const userForm = useForm({ name: '' }, {
  validators: {
    name: Validators.required(),
  }
});
  • We use useForm to create the form object, passing the initial state ({ name: '' }) and the validation rules object.
  • The validators object specifies that the name field requires a value using Validators.required().

Submitting the Form and Handling Validation

Here's an example onSubmit method that triggers form validation and handles successful or failed submissions:

onSubmit() {
  // Set form submission flag (strictly necessary with OnSubmit strategy)
  this.userForm.submit = true;

  if (this.userForm.valid) {
    // Form is valid, proceed with form submission logic (e.g., sending data to server)
    console.log('Form submitted successfully!');
  } else {
    // Form is invalid, display error messages to the user
    console.error('Form validation failed:', this.userForm.errors);

    // Optionally, display specific error messages near the corresponding form fields
  }
}

Explanation:

  1. this.userForm.submit = true; (Optional):
    • While strictly necessary with RunValidatorStrategy.OnSubmit, setting submit to true can be helpful for scenarios where you want to perform additional actions specifically when the submit button is clicked.
  2. if (this.userForm.valid):
    • This condition checks if the form is valid after the on-submit validation is triggered.
  3. console.log('Form submitted successfully!'):
    • If the form is valid, you can proceed with your form submission logic, such as sending data to a server or performing other necessary actions.
  4. console.error('Form validation failed:', this.userForm.errors):
    • If the form is invalid, error details are accessible through this.userForm.errors. You can log this information for debugging or display user-friendly error messages next to the corresponding form fields.