validEmail method

SimpleValidationBuilder<String> validEmail({
  1. String? message,
  2. String? code,
})

Adds a validation rule that checks if the String is a valid email address.

message is the error message returned if the validation fails. Defaults to "Invalid email address". code is an optional error code for translation purposes.

Returns the LucidValidationBuilder to allow for method chaining.

Example:

...
ruleFor((user) => user.email, key: 'email')
 .validEmail();

String format args:

  • {PropertyName}: The name of the property.

Implementation

SimpleValidationBuilder<String> validEmail({String? message, String? code}) {
  return use((value, entity) {
    if (RegExp(r'^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$').hasMatch(value)) {
      return null;
    }

    final currentCode = code ?? Language.code.validEmail;
    final currentMessage = LucidValidation.global.languageManager.translate(
      currentCode,
      parameters: {
        'PropertyName': label.isNotEmpty ? label : key,
      },
      defaultMessage: message,
    );

    return ValidationException(
      entity: extractClassName(entity.toString()),
      message: currentMessage,
      code: currentCode,
      key: key,
    );
  });
}