CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vuelidate--validators

Comprehensive validation library for Vue.js applications providing common validators with built-in error messages and customization options

87

1.14x
Overview
Eval results
Files

logical-operators.mddocs/

Logical Operators

Combinators for creating complex validation logic by combining multiple validators with logical operations.

Capabilities

AND Operator

Combines multiple validators where all must pass for the validation to succeed.

/**
 * Combines validators with logical AND - all validators must pass
 * @param validators - Array of validators to combine
 * @returns ValidationRuleWithoutParams that passes only when all validators pass
 */
function and<T = unknown>(...validators: ValidationRule<T>[]): ValidationRuleWithoutParams;

Usage Examples:

import { and, required, minLength, alpha } from "@vuelidate/validators";

// Combine multiple string validators
const strictNameValidation = and(
  required,
  minLength(2),
  alpha
);

// Test the combined validator
const validName = strictNameValidation("John"); // true (required ✓, length ✓, alpha ✓)
const invalidName1 = strictNameValidation(""); // false (required ✗)
const invalidName2 = strictNameValidation("A"); // false (minLength ✗)
const invalidName3 = strictNameValidation("John123"); // false (alpha ✗)

// In validation rules
const validationRules = {
  username: {
    strictValidation: and(
      required,
      minLength(3),
      alphaNum
    )
  }
};

OR Operator

Combines multiple validators where at least one must pass for the validation to succeed.

/**
 * Combines validators with logical OR - at least one validator must pass
 * @param validators - Array of validators to combine
 * @returns ValidationRuleWithoutParams that passes when any validator passes
 */
function or<T = unknown>(...validators: ValidationRule<T>[]): ValidationRuleWithoutParams;

Usage Examples:

import { or, email, url, numeric } from "@vuelidate/validators";

// Allow either email or URL format
const emailOrUrl = or(
  email,
  url
);

// Test the combined validator
const validEmail = emailOrUrl("user@example.com"); // true (email ✓)
const validUrl = emailOrUrl("https://example.com"); // true (url ✓)
const invalidBoth = emailOrUrl("invalid-format"); // false (both ✗)

// Complex OR combination
const flexibleIdValidation = or(
  numeric,
  and(alpha, minLength(5))
);

// In validation rules
const validationRules = {
  contactInfo: {
    emailOrUrl: or(email, url)
  },
  identifier: {
    flexibleId: or(
      numeric,
      and(alpha, minLength(3))
    )
  }
};

NOT Operator

Negates a validator result - passes when the wrapped validator fails.

/**
 * Negates validator result - passes when wrapped validator fails
 * @param validator - Validator to negate
 * @returns ValidationRuleWithoutParams that passes when wrapped validator fails
 */
function not<T = unknown>(validator: ValidationRule<T>): ValidationRuleWithoutParams;

Usage Examples:

import { not, numeric, email, required } from "@vuelidate/validators";

// Must NOT be numeric (e.g., for username field)
const notNumeric = not(numeric);

// Test the negated validator
const validUsername = notNumeric("john_doe"); // true (not numeric ✓)
const invalidUsername = notNumeric("12345"); // false (is numeric ✗)

// Must NOT be an email (for security code field)
const notEmail = not(email);

// Complex negation
const notRequiredOrEmpty = not(required);

// In validation rules
const validationRules = {
  username: {
    required: required,
    notNumeric: not(numeric)
  },
  displayName: {
    notEmail: not(email)
  },
  optionalField: {
    canBeEmpty: not(required) // This allows empty values
  }
};

Complex Logical Combinations

Nested Logical Operations

Logical operators can be nested to create sophisticated validation logic:

import { and, or, not, required, minLength, maxLength, alpha, numeric, email } from "@vuelidate/validators";

// Complex username validation:
// - Required AND
// - (Alphanumeric with 3-20 chars) OR (Email format)
// - NOT purely numeric
const complexUsernameValidation = and(
  required,
  or(
    and(alphaNum, minLength(3), maxLength(20)),
    email
  ),
  not(numeric)
);

// Password complexity:
// - Required AND
// - Minimum 8 characters AND
// - NOT purely alphabetic AND NOT purely numeric
const passwordComplexity = and(
  required,
  minLength(8),
  not(alpha),
  not(numeric)
);

Conditional Logic Patterns

import { and, or, not, required, requiredIf, email, url } from "@vuelidate/validators";

// Business contact validation:
// - If business account: require company email OR company website
// - If personal account: just require email
const businessContactValidation = or(
  and(
    requiredIf(computed(() => accountType.value === "business")),
    or(
      and(email, /* custom business email validator */),
      url
    )
  ),
  and(
    requiredIf(computed(() => accountType.value === "personal")),
    email
  )
);

Multi-Field Dependencies

import { and, or, required, requiredIf, sameAs } from "@vuelidate/validators";

const formData = ref({
  hasAlternateContact: false,
  primaryEmail: "",
  alternateEmail: "",
  phone: ""
});

const validationRules = {
  primaryEmail: { required, email },
  
  // Alternate contact must be provided if checkbox is checked
  // AND it must be either email OR phone
  // AND if email is provided, it must NOT be same as primary
  alternateContact: {
    validation: and(
      requiredIf(computed(() => formData.value.hasAlternateContact)),
      or(
        and(
          email,
          not(sameAs(computed(() => formData.value.primaryEmail)))
        ),
        phone // Assuming phone validator exists
      )
    )
  }
};

Best Practices

Readability and Maintenance

// Good: Break complex logic into named validators
const hasValidLength = and(minLength(3), maxLength(50));
const hasValidFormat = or(alphaNum, email);
const isNotRestricted = not(in(RESTRICTED_WORDS));

const usernameValidation = and(
  required,
  hasValidLength,
  hasValidFormat,
  isNotRestricted
);

// Less readable: Deeply nested inline
const usernameValidation2 = and(
  required,
  and(minLength(3), maxLength(50)),
  or(alphaNum, email),
  not(in(RESTRICTED_WORDS))
);

Error Message Considerations

import { helpers } from "@vuelidate/validators";

// Custom messages for complex logical validators
const complexValidation = helpers.withMessage(
  "Username must be 3-20 characters, alphanumeric or email format, and not purely numeric",
  and(
    required,
    or(
      and(alphaNum, minLength(3), maxLength(20)),
      email
    ),
    not(numeric)
  )
);

Performance Optimization

// Efficient: Put most likely to fail validators first
const efficientValidation = and(
  required, // Most likely to fail, check first
  minLength(8), // Quick length check
  expensiveCustomValidator() // Expensive operation last
);

// Less efficient: Expensive operations first
const inefficientValidation = and(
  expensiveCustomValidator(), // Runs even if required fails
  required,
  minLength(8)
);

Install with Tessl CLI

npx tessl i tessl/npm-vuelidate--validators

docs

conditional-validators.md

core-validators.md

format-validators.md

helpers-utilities.md

index.md

internationalization.md

logical-operators.md

tile.json