Null Value Handling

Understanding null value handling in validation

CBValidation handles null values carefully to ensure robust validation across nested structures and arrays. This guide explains how null values are treated during validation and filtering.

Overview

Null value handling (enhanced in 4.7.0-4.8.0) ensures that:

  • Null values don't cause validation errors unexpectedly

  • Nested structures and arrays properly filter null values

  • The validateOrFail() method returns clean, null-free results

Validation Rules for Nulls

Required Fields

Null values are treated as missing when required: true:

validation.bx
var constraints = {
    email: { required: true, type: "email" }
};

// ❌ FAILS - null is treated as missing
var result = validate(target={ email: javacast("null", "") }, constraints: constraints);
result.hasErrors();  // true - "email is required"

// ❌ FAILS - empty string is treated as missing
var result = validate(target={ email: "" }, constraints: constraints);
result.hasErrors();  // true - "email is required"

// ✅ PASSES - value provided
var result = validate(target={ email: "[email protected]" }, constraints: constraints);
result.hasErrors();  // false

Optional Fields with Type Checking

When required: false (default), null values are generally ignored by type validators:

Null Filtering in validateOrFail()

The validateOrFail() method filters out null values from results (4.7.0+). This ensures clean data:

{% code title="filterin

g-nulls.bx" overflow="wrap" lineNumbers="true" %}

Nested Structures with Nulls

When validating nested structures, null values in nested objects are properly handled:

Array Items with Nulls

Arrays are properly filtered when items contain null values:

Best Practices

1. Null Check Before Processing

Even after validation, check for nulls if you expect them:

2. Use Required for Important Fields

Always mark fields as required: true if they're critical:

3. Use defaultValue for Optional Fields

Apply sensible defaults for optional fields:

4. Clean Results with validateOrFail

Use validateOrFail() to get clean data without nulls:

Empty vs Null

Understand the distinction:

  • Null: javacast("null", "") - No value exists

  • Empty String: "" - Value exists but is blank

  • Zero: 0 or 0.0 - Valid numeric value

  • False: false - Valid boolean value

Most validators treat empty strings the same as null, except in special cases:

See Also

Last updated

Was this helpful?