Skip to main content

Validator

Validates the current value of the field.

Description​

This method must be implemented in subclasses to provide the validation logic for the field. It evaluates the field's value and determines its validity.

The method takes the current value of type T as input and returns:

  • An exception of type E if the value is invalid.
  • null if the value is valid.

Usage​

You must override this method in your custom field classes to implement specific validation rules.

Example 1: Basic Validation​

If the field value does not meet certain conditions, return an exception.

// class MyException ...



MyException? validator(MyValue value) {
if (value.isValid()) {
return null; // The value is valid
} else {
return MyException('Invalid value'); // The value is invalid
}
}

Example 2: Using FFormException for Advanced Validation​

If the exception type extends FFormException, you can include additional details like validity status or error messages:

// class MyException extends FFormException {
// ...
//}



MyException? validator(MyValue value) {
if (value.isValid()) {
return MyException(isValid: true); // Indicates the value is valid
} else {
return MyException(isValid: false, message: 'Invalid value'); // Indicates an invalid value with an error message
}
}

Returns​

  • E: An exception of type E with value valid or invalid.
  • null: When the field's value is valid.

When It's Used​

This method is invoked:

  • During the field's initialization when validation is required.
  • When the check method is called to validate the field's current value.
  • Automatically, when the field's value changes and needs re-validation.

Best Practices​

  • Ensure the exception provides meaningful information for debugging or user feedback.
  • Keep validation logic concise and focused on the specific rules for the field.
  • If your custom exception extends FFormException, consider adding properties like isValid or message to enhance debugging and user experience.

Notes​

  • The validator method is the core validation mechanism for a form field.
  • Implement custom validation logic specific to your application by overriding this method in subclasses.