📦 Valdation Box
Guide/Frameworks

Front-end

Validation Box works seamlessly with most JS/TS frameworks.

Front-end applications often require real-time input validation to improve user experience and prevent incorrect submissions. Validation Box helps enforce rules for usernames, emails, passwords, and phone numbers directly in UI components.

Validation Box is designed to be framework-agnostic, meaning it can work with other frontend libraries beyond React, Vue, and Svelte. If you're using Angular, Solid.js, or Alpine.js, you can likely integrate it with minor adjustments.

React & Next.js

React applications benefit from on-the-fly validation using Validation Box. In Next.js, remember to use "use client" at the top of your component.

Username Validation in React (Next.js Compatible):

"use client";
import { useState } from "react";
import { validateUsername } from "validation-box";
 
export default function UsernameValidator() {
  const [username, setUsername] = useState("");
  const [error, setError] = useState("");
 
  const handleValidation = () => {
    const result = validateUsername(username, {
      bannedWords: ["admin", "root"],
      messages: {
        bannedWords: "You are using prohibited words",
      },
    });
 
    setError(result.valid ? "" : result.errors?.[0] || "Invalid username!");
    console.log(result);
  };
 
  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="Enter your username"
      />
      <button onClick={handleValidation}>Validate</button>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </div>
  );
}  

Check the return of the console.

Schema

Now you can create structured validation using vboxSchema instead of calling each validator separately.

We are providing an example using React, but the same validation schema can be adapted to work with Vue as well. The validation logic remains consistent across different frameworks, ensuring flexibility and reusability of the schema.
"use client"
import React, { useState } from "react";
import { vboxSchema, validator } from "validation-box";
 
const userSchema = new vboxSchema({
  username: validator.username({
    bannedWords: ["admin", "root"],
    messages: { bannedWords: "You are using prohibited words"},
  }),
  password: validator.password({
    min: 8,
    messages: { invalidFormat: "Invalid Password" },
  }),
});
 
const UserRegistrationForm: React.FC = () => {
  const [formData, setFormData] = useState({
    username: "",
    password: "",
  });
  const [errors, setErrors] = useState<Record<string, string[]>>({});
 
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({ ...prevData, [name]: value }));
  };
 
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const result = userSchema.validate(formData);
    if (result.success) {
      console.log("Form data is valid:", result.data);
      setErrors({});
    } else {
      console.log("Form data is invalid:", result.errors);
      setErrors(result.errors || {});
    }
  };
 
  return (
    <form onSubmit={handleSubmit}>
      <div>
          <input
            type="text"
            name="username"
            value={formData.username}
            onChange={handleChange}
            placeholder="Enter username"
          />
        {errors.username && <p>{errors.username}</p>}
      </div>
      <div>
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            placeholder="Enter password"
          />
        {errors.password && <p>{errors.password}</p>}
      </div>
      <button type="submit">Login</button>
    </form>
  );
};
 
export default UserRegistrationForm;

Vue & Nuxt.js

Vue applications, including Nuxt.js, can easily integrate Validation Box with Vue’s reactivity system (ref).

Email Validation in Vue (Compatible with Nuxt 3):

<script setup>
import { ref } from "vue";
import { validateEmail } from "validation-box";
 
const email = ref("");
const message = ref("");
 
const handleValidation = () => {
  const result = validateEmail(email.value, {
    allowedDomains: ["gmail.com", "outlook.com"],
    messages: {
      allowedDomains: "Only Gmail or Outlook emails are allowed",
    }
  });
 
  if (result.valid) {
    message.value = "✅ Valid email!";
  } else {
    message.value = result.errors?.[0] || "❌ Invalid email!";
  }
};
</script>
 
<template>
  <div>
    <input v-model="email" placeholder="Enter your email" />
    <button @click="handleValidation">Validate</button>
    <p v-if="message">{{ message }}</p>
  </div>
</template>

Svelte

Svelte makes validation simpler by directly binding values to input fields.

Phone Number (Angola) Validation in Svelte

<script>
  import { validatePhoneAO } from "validation-box";
 
  let phone = "";
  let error = "";
 
  function handleValidation() {
    error = validatePhoneAO(phone)
      ? "Valid phone number."
      : "Invalid phone number.";
  }
</script>
 
<input bind:value={phone} placeholder="Enter phone number" />
<button on:click={handleValidation}>Validate</button>
<p>{error}</p>

Want to extend support? If you test Validation Box with another frontend framework and it works, consider submitting an example to our documentation!

On this page