Blog>
Snippets

Enhancing Security with Custom Hooks for Password Strength

Provide an example of a custom hook that integrates with TanStack Form to assess and improve password strength before form submission.
import { useForm, useField } from 'tanstack-form-core';

// Custom hook to validate password strength
function usePasswordStrength() {
  return useField({
    // Define the validation for the password field
    validate: async (value) => {
      const strongRegex = new RegExp('^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$');
      if (!strongRegex.test(value)) {
        return 'Password must be at least 8 characters long and include uppercase letters, lowercase letters, and numbers.';
      }
    }
  });
}
This code snippet defines a custom hook using TanStack Form's useField hook. The usePasswordStrength hook validates a password field based on specified criteria: at least 8 characters long, with uppercase letters, lowercase letters, and numbers. This enhances form security by ensuring users set strong passwords.
const { formContext } = useForm({
  // Initialize the form
});

// Inside your form component
const password = usePasswordStrength();

// To use it in a form field
<input {...password.getInputProps()} type='password' placeholder='Password' />;
This code snippet shows how to integrate the custom usePasswordStrength hook with a form using TanStack Form. First, a form instance is created with useForm. Then, the password field is initialized with usePasswordStrength, and its properties are spread into an input element to enforce the custom validation logic.