JavaScript275 Documents

Ensure Validation

Use the shared ensure API for data validation at every layer whenever it can express the requirement. Reuse an existing rule or satisfies predicate when appropriate. When a reusable validation capability is missing, propose an extension to ensure before writing manual if/else checks that raise errors. Use manual checks only when the existing API and a reasonable extension cannot meet the requirement. Pass an existing field-label translation key when the message needs to identify the input, such as ensure(category, 'category').isSomething(). Reuse shared ICU validation templates and translate their field-label arguments instead of creating a new error key for every field. JavaScript receives the value rather than the caller’s variable name, so provide the key explicitly; unnamed values use the shared value label. Default ICU messages must explain the failing rule and include relevant length, numeric or date bounds without exposing the input value. For a custom satisfies predicate, supply a reusable localized message key when its business-specific condition needs a more precise explanation. Use the Explicit Input Errors policy only for a reviewed fallback when the shared API and a reasonable extension cannot meet the requirement. This policy concerns validation, not ordinary business branching or rendering conditions.

Philosophy

Validation rules and their messages should have one shared implementation. Fluent validation keeps callers declarative, while reusable ICU templates identify the input without multiplying translation keys across fields and locales.

Correct

ensure(category, 'category').isSomething()
ensure(email, 'email').isSomething().and.isEmail()
ensure(quantity, 'quantity').isNaturalNumber()
ensure(category, 'category').satisfies(value => typeof value === 'string')

Incorrect

if (isNothing(category)) {
    clientError('missingCategory')
}

if (typeof email !== 'string') clientError('invalidEmail')

Exceptions

  • The shared ensure implementation and its boolean predicates may use conditionals to implement validation rules.

Fix

Replace manual validation with the appropriate ensure chain and an existing field-label key. Propose a reusable ensure extension before falling back to manual validation.