Skip to main content

C2CStringValidator

The C2CStringValidator class is a utility for validating and manipulating string values in Flutter applications.

Constructor

C2CStringValidator()

Creates a new instance of the validator with optional settings.

  • trim: A boolean flag indicating whether leading and trailing whitespace should be trimmed from the input string.
  • convertCase: An optional enum value of type ConvertCase (either lowercase or uppercase) to specify if the input string should be converted to lowercase or uppercase.

Factory Constructors

C2CStringValidator.required(String requiredMessage)

Creates a required instance of the validator with a custom error message for cases where the input is empty or null.

  • requiredMessage: A custom error message to be displayed when the input is required but empty.

Validation Methods

add(validator)

Adds a custom validation function to the validator. The function should take a string input and return a string (an error message) if the input is invalid or null if it's valid.

C2CStringValidator()
.add((value) => value == null || value.isEmpty ? "Error message" : null)
.validate("Test value");

compare(condition, message)

Adds a conditional validation rule. It takes a condition function and an error message. If the condition function returns true, the input is considered valid; otherwise, the error message is returned.

const anotherValue = "Hello world";
C2CStringValidator()
.compare((value) => value == anotherValue, "Error message")
.validate("test value");

when(condition, then, otherwise)

Adds conditional validation with branching. It takes a condition function, and two callbacks to configure validators for the "then" and "otherwise" branches. Depending on the condition, one of the branch validators is applied.

const anotherValue = "Hello world";
C2CStringValidator()
.when(
condition: (value) => value == anotherValue,
then: (builder) => builder.min(20, "Min length is 20"),
otherwise: (builder) => builder.min(30, "Min length is 30"),
)
.validate("test value")

oneOf(values, message)

Validates if the input string is included in a list of allowed values. If the input is in the list, it's considered valid; otherwise, an error message is returned.

List<String> validValues = ["one", "two", "three", "four"];
C2CStringValidator().oneOf(validValues, "Error message").validate("five");

notOneOf(values, message)

Validates if the input string is not included in a list of disallowed values. If the input is not in the list, it's considered valid; otherwise, an error message is returned.

List<String> validValues = ["one", "two", "three", "four"];
C2CStringValidator()
.notOneOf(validValues, "Error message")
.validate("one");

length(length, message)

Sets a required length for the input string. If the length of the input string does not match the specified length, an error message is returned.

C2CStringValidator().length(3, "Error message").validate("test");

min(limit, message)

Sets a minimum length limit for the input string. If the length of the input string is less than the specified limit, an error message is returned.

C2CStringValidator().min(5, "Error message").validate("test");

max(limit, message)

Sets a maximum length limit for the input string. If the length of the input string exceeds the specified limit, an error message is returned.

C2CStringValidator().max(3, "Error message").validate("test");

matches(regExp, message)

Validates if the input string matches a regular expression pattern. If the pattern is matched, the input is considered valid; otherwise, an error message is returned.

C2CStringValidator()
.matches(RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$'),
"Minimum 8 characters, at least 1 letter and 1 number")
.validate("test");

or(left, right, {reverse})

Combines two validators using a logical OR operation. If either the left or right validator passes, the combined validator passes.

  • left: A callback that configures the left validator.
  • right: A callback that configures the right validator.
  • reverse: An optional boolean flag. If true, it returns the result of the left validator if both the left and right validators pass.
// The value is valid if it's Japanese text or Katakana text.
C2CStringValidator().or(
(builder) => builder.japaneseText("Japanese text"),
(builder) => builder.katakanaText("Katakana text"),
).validate("カタカナ");

Example Usage

// Validation rules:
// - Required field (null or empty string)
// - Minimum length of 4 characters.
// - Maximum length of 20 characters.
// - Not one of the predefined `values`.
List<String> values = ["admin", "user", "administrator", "test"];
C2CStringValidator.required("Field is required")
.min(4, "Minimum 4 characters")
.max(20, "Maximum 20 characters")
.notOneOf(values, "Value is not one of ${values.join(',')}")
.validate("test");

// Create a custom validation rule using the 'add' method.
// The custom rule checks if the input contains "123" and returns an error message if it does.
C2CStringValidator()
.add((value) {
if (value != null && value.contains("123")) {
return "Input cannot contain '123'";
}
return null; // No validation error
}).validate("test");

// Create a validator that converts the input to uppercase.
C2CStringValidator(convertCase: ConvertCase.uppercase)
.compare((value) => value == "TEST", "Error message")
.validate("test");

Extension: CommonRegexValidator

The CommonRegexValidator extension provides pre-defined validation rules for common string formats. These rules include:

  • email: Validates if the input is a valid email address.
  • phone: Validates if the input is a valid phone number.
  • password: Validates if the input is a valid password.
  • url: Validates if the input is a valid URL.
  • japaneseText: Validates if the input contains Japanese text.
  • katakanaText: Validates if the input contains Katakana text.
  • bankAccountName: Validates if the input is a valid bank account name.
  • uuid: Validates if the input is a valid UUID.
// Validate email
// ^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$
C2CStringValidator.required("Field is required", trim: true)
.email("Invalid email address")
.validate("test");

// Validate password
// ((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).{8,}$
C2CStringValidator.required("Field is required")
.password("Invalid password")
.validate("test");

Add more case:

extension ProjectRegexValidator on C2CStringValidator {
static final RegExp passwordRegex = RegExp(
r"^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$",
);

/// Validate the value as a password.
C2CStringValidator projectPassword(String message) =>
add((v) => passwordRegex.hasMatch(v!) ? null : message);
}

// Validate
C2CStringValidator.required("Field is required", trim: true)
.projectPassword("Invalid password")
.validate("test")