Rule class abstract

The Rule Contract.

This is the foundation of Magic's validation system. Every validation rule must implement this contract, giving you a clean and predictable API whether you're using built-in rules or creating your own.

Creating a Custom Rule

class Uppercase extends Rule {
  @override
  bool passes(String attribute, dynamic value, Map<String, dynamic> data) {
    if (value is! String) return false;
    return value == value.toUpperCase();
  }

  @override
  String message() => 'validation.uppercase';
  // Or a raw message: 'The :attribute must be uppercase.'
}

Message Resolution

The message() method can return either:

  • A translation key (e.g., 'validation.required') - resolved via Lang.get()
  • A raw string (e.g., 'This field is required.') - used as-is

Parameters

Override params() to provide replacement values for your message:

class Min extends Rule {
  final int min;
  Min(this.min);

  @override
  Map<String, dynamic> params() => {'min': min};
}
// Message: "The :attribute must be at least :min characters."
// Result:  "The name must be at least 3 characters."
Implementers

Constructors

Rule()
Lets a rule that carries no mutable state declare a const constructor.
const

Properties

hashCode int
The hash code for this object.
no setterinherited
name String
The short name this rule is known by in a messages override map.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

message() String
Get the validation error message.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
params() Map<String, dynamic>
Get the replacement parameters for the message.
passes(String attribute, dynamic value, Map<String, dynamic> data) bool
Determine if the validation rule passes.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited