Blog>
Snippets

Implementing Custom Validation Logic

Show how to implement custom validation logic for a form field, including both synchronous and asynchronous validation methods.
const validateSync = (value) => value.length >= 8 ? '' : 'Must be at least 8 characters';
Defines a synchronous validation function for a field, here ensuring a text has at least 8 characters.
const validateAsync = async (value) => {
  const response = await fetch(`/api/validate?fieldValue=${value}`);
  const { isValid, errorMessage } = await response.json();
  return isValid ? '' : errorMessage;
};
Defines an asynchronous validation, for instance, checking if a username is already taken by making an API call.
const handleSubmit = async (event) => {
  event.preventDefault();
  const value = event.target.myField.value;
  const syncError = validateSync(value);
  if (syncError) {
    alert(syncError);
    return;
  }
  const asyncError = await validateAsync(value);
  if (asyncError) {
    alert(asyncError);
    return;
  }
  // submit form data
};
Integrates the validation functions within a submit event handler for a form, checking first for synchronous errors then for asynchronous ones before submission.