From 619be1390c1b11cdeff3a8749dba3de3b3019010 Mon Sep 17 00:00:00 2001 From: Jacob Moura Date: Tue, 8 Oct 2024 19:57:16 -0300 Subject: [PATCH] Added Label --- CHANGELOG.md | 4 ++ .../lib/domain/dtos/register_param_dto.dart | 3 +- .../domain/validations/language_manager.dart | 12 ++-- .../register_param_validation.dart | 6 +- .../presentation/login_page/login_page.dart | 6 +- .../register_page/register_page.dart | 6 +- example/pubspec.lock | 6 +- lib/src/localization/culture.dart | 3 +- lib/src/localization/language.dart | 51 +++++++++----- lib/src/localization/language_manager.dart | 11 +++- .../portuguese_brazillian_language.dart | 66 ++++++++++++------- .../languages/spanish_language.dart | 66 ++++++++++++------- lib/src/lucid_validation_builder.dart | 12 ++-- lib/src/lucid_validator.dart | 15 +++-- lib/src/validations/equal_validation.dart | 2 +- ...exclusive_between_datetime_validation.dart | 5 +- .../greater_than_datetime_validation.dart | 2 +- ..._than_or_equal_to_datetime_validation.dart | 8 ++- .../validations/greater_than_validation.dart | 2 +- ...inclusive_between_datetime_validation.dart | 9 ++- lib/src/validations/is_empty_validation.dart | 2 +- .../validations/is_not_null_validation.dart | 2 +- lib/src/validations/is_null_validation.dart | 2 +- .../less_than_datetime_validation.dart | 2 +- ..._than_or_equal_to_datetime_validation.dart | 8 ++- lib/src/validations/less_then_validation.dart | 5 +- .../matches_pattern_validation.dart | 5 +- .../validations/max_length_validation.dart | 5 +- lib/src/validations/max_validation.dart | 2 +- .../validations/min_length_validation.dart | 5 +- lib/src/validations/min_validation.dart | 2 +- .../must_have_lowercase_validation.dart | 5 +- .../must_have_number_validation.dart | 5 +- ...ust_have_special_character_validation.dart | 8 ++- .../must_have_uppercase_validation.dart | 5 +- lib/src/validations/not_empty_validation.dart | 2 +- lib/src/validations/not_equal_validation.dart | 5 +- lib/src/validations/range_validation.dart | 5 +- lib/src/validations/valid_cep_validation.dart | 2 +- .../validations/valid_cnpj_validation.dart | 2 +- lib/src/validations/valid_cpf_validation.dart | 2 +- .../valid_creditcard_validation.dart | 5 +- .../validations/valid_email_validation.dart | 2 +- pubspec.yaml | 2 +- test/byfield_validation_test.dart | 41 ++++++++---- test/lucid_validation_test.dart | 20 ++++-- test/mocks/mocks.dart | 12 ++-- .../validations/equal_validation_test.dart | 7 +- ...sive_between_datetime_validation_test.dart | 18 +++-- ...greater_than_datetime_validation_test.dart | 3 +- ..._or_equal_to_datetime_validation_test.dart | 3 +- ...sive_between_datetime_validation_test.dart | 3 +- .../less_than_datetime_validation_test.dart | 3 +- ..._or_equal_to_datetime_validation_test.dart | 3 +- .../matches_pattern_validation_test.dart | 3 +- .../max_length_validation_test.dart | 3 +- test/src/validations/max_validation_test.dart | 3 +- .../min_length_validation_test.dart | 3 +- test/src/validations/min_validation_test.dart | 3 +- .../must_have_lowercase_validation_test.dart | 3 +- .../must_have_number_validation_test.dart | 3 +- ...ave_special_character_validation_test.dart | 3 +- .../must_have_uppercase_validation_test.dart | 3 +- .../not_equal_validation_test.dart | 3 +- .../valid_email_validation_test.dart | 4 +- 65 files changed, 350 insertions(+), 182 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7271cf0..1d9915c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 1.1.0 + +* Added Label + ## 1.0.1 * Added valid greaterThanOrEqualTo, greaterThan, lessThanOrEqualTo, lessThan, inclusiveBetween and exclusiveBetween diff --git a/example/lib/domain/dtos/register_param_dto.dart b/example/lib/domain/dtos/register_param_dto.dart index ccbb5ef..23a724c 100644 --- a/example/lib/domain/dtos/register_param_dto.dart +++ b/example/lib/domain/dtos/register_param_dto.dart @@ -21,7 +21,8 @@ class RegisterParamDto extends ChangeNotifier { _password = password, _confirmPassword = confirmPassword; - factory RegisterParamDto.empty() => RegisterParamDto(email: '', password: '', phone: '', confirmPassword: ''); + factory RegisterParamDto.empty() => + RegisterParamDto(email: '', password: '', phone: '', confirmPassword: ''); void setEmail(String value) { _email = value; diff --git a/example/lib/domain/validations/language_manager.dart b/example/lib/domain/validations/language_manager.dart index 09a7722..a045aa1 100644 --- a/example/lib/domain/validations/language_manager.dart +++ b/example/lib/domain/validations/language_manager.dart @@ -2,9 +2,13 @@ import 'package:lucid_validation/lucid_validation.dart'; class CustomLanguageManager extends LanguageManager { CustomLanguageManager() { - addTranslation(Culture('pt', 'BR'), 'passwordEqualTo', "'{PropertyName}' deve ser igual."); - addTranslation(Culture('pt'), 'passwordEqualTo', "'{PropertyName}' deve ser igual."); - addTranslation(Culture('en', 'US'), 'passwordEqualTo', "'{PropertyName}' must be equal."); - addTranslation(Culture('en'), 'passwordEqualTo', "'{PropertyName}' must be equal."); + addTranslation(Culture('pt', 'BR'), 'passwordEqualTo', + "'{PropertyName}' deve ser igual."); + addTranslation( + Culture('pt'), 'passwordEqualTo', "'{PropertyName}' deve ser igual."); + addTranslation(Culture('en', 'US'), 'passwordEqualTo', + "'{PropertyName}' must be equal."); + addTranslation( + Culture('en'), 'passwordEqualTo', "'{PropertyName}' must be equal."); } } diff --git a/example/lib/domain/validations/register_param_validation.dart b/example/lib/domain/validations/register_param_validation.dart index f698da9..ce651cc 100644 --- a/example/lib/domain/validations/register_param_validation.dart +++ b/example/lib/domain/validations/register_param_validation.dart @@ -11,9 +11,11 @@ class RegisterParamValidation extends LucidValidator { ruleFor((registerParamDto) => registerParamDto.password, key: 'password') // .customValidPassword(); - ruleFor((registerParamDto) => registerParamDto.confirmPassword, key: 'confirmPassword') // + ruleFor((registerParamDto) => registerParamDto.confirmPassword, + key: 'confirmPassword') // .customValidPassword() - .equalTo((registerParamDto) => registerParamDto.password, code: 'passwordEqualTo'); + .equalTo((registerParamDto) => registerParamDto.password, + code: 'passwordEqualTo'); ruleFor((registerParamDto) => registerParamDto.phone, key: 'phone') // .customValidPhone(); diff --git a/example/lib/presentation/login_page/login_page.dart b/example/lib/presentation/login_page/login_page.dart index 301a81f..54252ed 100644 --- a/example/lib/presentation/login_page/login_page.dart +++ b/example/lib/presentation/login_page/login_page.dart @@ -49,7 +49,8 @@ class _LoginPageState extends State { return Switch( value: globalLocale.value.languageCode == 'en', onChanged: (value) { - globalLocale.value = value ? Locale('en', 'US') : Locale('pt', 'BR'); + globalLocale.value = + value ? Locale('en', 'US') : Locale('pt', 'BR'); }, ); }), @@ -97,7 +98,8 @@ class _LoginPageState extends State { onPressed: () { Navigator.push( context, - MaterialPageRoute(builder: (context) => const RegisterPage()), + MaterialPageRoute( + builder: (context) => const RegisterPage()), ); }, child: const Text('Sign up'), diff --git a/example/lib/presentation/register_page/register_page.dart b/example/lib/presentation/register_page/register_page.dart index 467626c..2994362 100644 --- a/example/lib/presentation/register_page/register_page.dart +++ b/example/lib/presentation/register_page/register_page.dart @@ -47,7 +47,8 @@ class _RegisterPageState extends State { /// call to api passing the parameter loginParamDto ScaffoldMessenger.of(context).showSnackBar(sucessSnackBar()); } else { - ScaffoldMessenger.of(context).showSnackBar(failureSnackBar(result.exceptions.first.message)); + ScaffoldMessenger.of(context) + .showSnackBar(failureSnackBar(result.exceptions.first.message)); } } @@ -67,7 +68,8 @@ class _RegisterPageState extends State { return Switch( value: globalLocale.value.languageCode == 'en', onChanged: (value) { - globalLocale.value = value ? Locale('en', 'US') : Locale('pt', 'BR'); + globalLocale.value = + value ? Locale('en', 'US') : Locale('pt', 'BR'); }, ); }), diff --git a/example/pubspec.lock b/example/pubspec.lock index 5f10222..5293f04 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -126,7 +126,7 @@ packages: path: ".." relative: true source: path - version: "0.0.7" + version: "1.0.1" matcher: dependency: transitive description: @@ -224,10 +224,10 @@ packages: dependency: transitive description: name: vm_service - sha256: f652077d0bdf60abe4c1f6377448e8655008eef28f128bc023f7b5e8dfeb48fc + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" url: "https://pub.dev" source: hosted - version: "14.2.4" + version: "14.2.5" sdks: dart: ">=3.4.3 <4.0.0" flutter: ">=3.18.0-18.0.pre.54" diff --git a/lib/src/localization/culture.dart b/lib/src/localization/culture.dart index 4921cff..1a1870d 100644 --- a/lib/src/localization/culture.dart +++ b/lib/src/localization/culture.dart @@ -9,7 +9,8 @@ class Culture { bool operator ==(covariant Culture other) { if (identical(this, other)) return true; - return other.languageCode == languageCode && other.countryCode == countryCode; + return other.languageCode == languageCode && + other.countryCode == countryCode; } @override diff --git a/lib/src/localization/language.dart b/lib/src/localization/language.dart index c9f0439..96ba4b5 100644 --- a/lib/src/localization/language.dart +++ b/lib/src/localization/language.dart @@ -37,34 +37,51 @@ abstract class Language { final _translations = { code.equalTo: "'{PropertyName}' must be equal to '{ComparisonValue}'.", - code.greaterThan: "'{PropertyName}' must be greater than '{ComparisonValue}'.", + code.greaterThan: + "'{PropertyName}' must be greater than '{ComparisonValue}'.", code.isEmpty: "'{PropertyName}' must be empty.", code.isNotNull: "'{PropertyName}' must not be null.", code.isNull: "'{PropertyName}' must be null.", code.lessThan: "'{PropertyName}' must be less than '{ComparisonValue}'.", code.matchesPattern: "'{PropertyName}' is not in the correct format.", - code.max: "'{PropertyName}' must be less than or equal to {MaxValue}. You entered {PropertyValue}.", - code.maxLength: "The length of '{PropertyName}' must be {MaxLength} characters or fewer. You entered {TotalLength} characters.", - code.min: "'{PropertyName}' must be greater than or equal to {MinValue}. You entered {PropertyValue}.", - code.minLength: "The length of '{PropertyName}' must be at least {MinLength} characters. You entered {TotalLength} characters.", - code.mustHaveLowercase: "'{PropertyName}' must have at least one lowercase letter.", - code.mustHaveNumber: "'{PropertyName}' must have at least one digit ('0'-'9').", - code.mustHaveSpecialCharacter: "'{PropertyName}' must have at least one non-alphanumeric character.", - code.mustHaveUppercase: "'{PropertyName}' must have at least one uppercase letter.", + code.max: + "'{PropertyName}' must be less than or equal to {MaxValue}. You entered {PropertyValue}.", + code.maxLength: + "The length of '{PropertyName}' must be {MaxLength} characters or fewer. You entered {TotalLength} characters.", + code.min: + "'{PropertyName}' must be greater than or equal to {MinValue}. You entered {PropertyValue}.", + code.minLength: + "The length of '{PropertyName}' must be at least {MinLength} characters. You entered {TotalLength} characters.", + code.mustHaveLowercase: + "'{PropertyName}' must have at least one lowercase letter.", + code.mustHaveNumber: + "'{PropertyName}' must have at least one digit ('0'-'9').", + code.mustHaveSpecialCharacter: + "'{PropertyName}' must have at least one non-alphanumeric character.", + code.mustHaveUppercase: + "'{PropertyName}' must have at least one uppercase letter.", code.notEmpty: "'{PropertyName}' must not be empty.", - code.notEqualTo: "'{PropertyName}' must not be equal to '{ComparisonValue}'.", - code.range: "'{PropertyName}' must be between {From} and {To}. You entered {PropertyValue}.", + code.notEqualTo: + "'{PropertyName}' must not be equal to '{ComparisonValue}'.", + code.range: + "'{PropertyName}' must be between {From} and {To}. You entered {PropertyValue}.", code.validCEP: "'{PropertyName}' is not a valid CEP.", code.validCPF: "'{PropertyName}' is not a valid CPF.", code.validCNPJ: "'{PropertyName}' is not a valid CNPJ.", code.validCreditCard: "'{PropertyName}' is not a valid credit card number.", code.validEmail: "'{PropertyName}' is not a valid email address.", - code.greaterThanOrEqualToDateTime: "'{PropertyName}' must be greater than or equal to date '{ComparisonValue}'.", - code.greaterThanDatetime: "'{PropertyName}' must be greater than date '{ComparisonValue}'.", - code.lessThanOrEqualToDateTime: "'{PropertyName}' must be less than or equal to date '{ComparisonValue}'.", - code.lessThanDateTime: "'{PropertyName}' must be less than date '{ComparisonValue}'.", - code.inclusiveBetweenDatetime: "'{PropertyName}' must be greater than or equal to '{StartValue}' date and less than or equal to '{EndValue}' date.", - code.exclusiveBetweenDatetime: "'{PropertyName}' must be greater than the '{StartValue}' date and less than the '{EndValue}' date." + code.greaterThanOrEqualToDateTime: + "'{PropertyName}' must be greater than or equal to date '{ComparisonValue}'.", + code.greaterThanDatetime: + "'{PropertyName}' must be greater than date '{ComparisonValue}'.", + code.lessThanOrEqualToDateTime: + "'{PropertyName}' must be less than or equal to date '{ComparisonValue}'.", + code.lessThanDateTime: + "'{PropertyName}' must be less than date '{ComparisonValue}'.", + code.inclusiveBetweenDatetime: + "'{PropertyName}' must be greater than or equal to '{StartValue}' date and less than or equal to '{EndValue}' date.", + code.exclusiveBetweenDatetime: + "'{PropertyName}' must be greater than the '{StartValue}' date and less than the '{EndValue}' date." }; String? getTranslation(String key) => _translations[key]; diff --git a/lib/src/localization/language_manager.dart b/lib/src/localization/language_manager.dart index 1a6d227..00ee341 100644 --- a/lib/src/localization/language_manager.dart +++ b/lib/src/localization/language_manager.dart @@ -61,14 +61,19 @@ abstract class LanguageManager { } bool isSupported(String languageCode, String? countryCode) { - return _avaliableLanguages.containsKey(Culture(languageCode, countryCode ?? '')); + return _avaliableLanguages + .containsKey(Culture(languageCode, countryCode ?? '')); } - String translate(String key, {Map parameters = const {}, String? defaultMessage}) { + String translate(String key, + {Map parameters = const {}, String? defaultMessage}) { final culture = LucidValidation.global.culture; final currentLanguage = getLanguage(culture); final translations = _globalTranslations[culture] ?? {}; - var message = defaultMessage ?? translations[key] ?? currentLanguage.getTranslation(key) ?? key; + var message = defaultMessage ?? + translations[key] ?? + currentLanguage.getTranslation(key) ?? + key; for (var key in parameters.keys) { final value = parameters[key]!; message = message.replaceAll('{$key}', value); diff --git a/lib/src/localization/languages/portuguese_brazillian_language.dart b/lib/src/localization/languages/portuguese_brazillian_language.dart index 55c090f..dae97ad 100644 --- a/lib/src/localization/languages/portuguese_brazillian_language.dart +++ b/lib/src/localization/languages/portuguese_brazillian_language.dart @@ -3,34 +3,56 @@ import '../language.dart'; class PortugueseBrasillianLanguage extends Language { PortugueseBrasillianLanguage() : super({ - Language.code.equalTo: "'{PropertyName}' deve ser igual a '{ComparisonValue}'.", - Language.code.greaterThan: "'{PropertyName}' deve ser maior que '{ComparisonValue}'.", + Language.code.equalTo: + "'{PropertyName}' deve ser igual a '{ComparisonValue}'.", + Language.code.greaterThan: + "'{PropertyName}' deve ser maior que '{ComparisonValue}'.", Language.code.isEmpty: "'{PropertyName}' deve estar vazio.", Language.code.isNotNull: "'{PropertyName}' não pode ser nulo.", Language.code.isNull: "'{PropertyName}' deve ser nulo.", - Language.code.lessThan: "'{PropertyName}' deve ser menor que '{ComparisonValue}'.", - Language.code.matchesPattern: "'{PropertyName}' não está no formato correto.", - Language.code.max: "'{PropertyName}' deve ser menor ou igual a {MaxValue}. Você digitou {PropertyValue}.", - Language.code.maxLength: "O tamanho de '{PropertyName}' deve ser de {MaxLength} caracteres ou menos. Você digitou {TotalLength} caracteres.", - Language.code.min: "'{PropertyName}' deve ser maior ou igual a {MinValue}. Você digitou {PropertyValue}.", - Language.code.minLength: "O tamanho de '{PropertyName}' deve ser de pelo menos {MinLength} caracteres. Você digitou {TotalLength} caracteres.", - Language.code.mustHaveLowercase: "'{PropertyName}' deve ter pelo menos uma letra minúscula.", - Language.code.mustHaveNumber: "'{PropertyName}' deve ter pelo menos um dígito ('0'-'9').", - Language.code.mustHaveSpecialCharacter: "'{PropertyName}' deve ter pelo menos um caractere não alfanumérico.", - Language.code.mustHaveUppercase: "'{PropertyName}' deve ter pelo menos uma letra maiúscula.", + Language.code.lessThan: + "'{PropertyName}' deve ser menor que '{ComparisonValue}'.", + Language.code.matchesPattern: + "'{PropertyName}' não está no formato correto.", + Language.code.max: + "'{PropertyName}' deve ser menor ou igual a {MaxValue}. Você digitou {PropertyValue}.", + Language.code.maxLength: + "O tamanho de '{PropertyName}' deve ser de {MaxLength} caracteres ou menos. Você digitou {TotalLength} caracteres.", + Language.code.min: + "'{PropertyName}' deve ser maior ou igual a {MinValue}. Você digitou {PropertyValue}.", + Language.code.minLength: + "O tamanho de '{PropertyName}' deve ser de pelo menos {MinLength} caracteres. Você digitou {TotalLength} caracteres.", + Language.code.mustHaveLowercase: + "'{PropertyName}' deve ter pelo menos uma letra minúscula.", + Language.code.mustHaveNumber: + "'{PropertyName}' deve ter pelo menos um dígito ('0'-'9').", + Language.code.mustHaveSpecialCharacter: + "'{PropertyName}' deve ter pelo menos um caractere não alfanumérico.", + Language.code.mustHaveUppercase: + "'{PropertyName}' deve ter pelo menos uma letra maiúscula.", Language.code.notEmpty: "'{PropertyName}' não pode estar vazio.", - Language.code.notEqualTo: "'{PropertyName}' não pode ser igual a '{ComparisonValue}'.", - Language.code.range: "'{PropertyName}' deve estar entre {From} e {To}. Você digitou {PropertyValue}.", + Language.code.notEqualTo: + "'{PropertyName}' não pode ser igual a '{ComparisonValue}'.", + Language.code.range: + "'{PropertyName}' deve estar entre {From} e {To}. Você digitou {PropertyValue}.", Language.code.validCEP: "'{PropertyName}' não é um CEP válido.", Language.code.validCPF: "'{PropertyName}' não é um CPF válido.", Language.code.validCNPJ: "'{PropertyName}' não é um CNPJ válido.", - Language.code.validCreditCard: "'{PropertyName}' não é um número de cartão de crédito válido.", - Language.code.validEmail: "'{PropertyName}' não é um endereço de e-mail válido.", - Language.code.greaterThanOrEqualToDateTime: "'{PropertyName}' deve ser maior ou igual à data '{ComparisonValue}'.", - Language.code.greaterThanDatetime: "'{PropertyName}' deve ser maior que a data '{ComparisonValue}'.", - Language.code.lessThanOrEqualToDateTime: "'{PropertyName}' deve ser menor ou igual à data '{ComparisonValue}'.", - Language.code.lessThanDateTime: "'{PropertyName}' deve ser menor que a data '{ComparisonValue}'.", - Language.code.inclusiveBetweenDatetime: "'{PropertyName}' deve ser maior ou igual à data '{StartValue}' e menor ou igual à data '{EndValue}'.", - Language.code.exclusiveBetweenDatetime: "'{PropertyName}' deve ser maior que a data '{StartValue}' e menor que a data '{EndValue}'." + Language.code.validCreditCard: + "'{PropertyName}' não é um número de cartão de crédito válido.", + Language.code.validEmail: + "'{PropertyName}' não é um endereço de e-mail válido.", + Language.code.greaterThanOrEqualToDateTime: + "'{PropertyName}' deve ser maior ou igual à data '{ComparisonValue}'.", + Language.code.greaterThanDatetime: + "'{PropertyName}' deve ser maior que a data '{ComparisonValue}'.", + Language.code.lessThanOrEqualToDateTime: + "'{PropertyName}' deve ser menor ou igual à data '{ComparisonValue}'.", + Language.code.lessThanDateTime: + "'{PropertyName}' deve ser menor que a data '{ComparisonValue}'.", + Language.code.inclusiveBetweenDatetime: + "'{PropertyName}' deve ser maior ou igual à data '{StartValue}' e menor ou igual à data '{EndValue}'.", + Language.code.exclusiveBetweenDatetime: + "'{PropertyName}' deve ser maior que a data '{StartValue}' e menor que a data '{EndValue}'." }); } diff --git a/lib/src/localization/languages/spanish_language.dart b/lib/src/localization/languages/spanish_language.dart index a2fafef..372e452 100644 --- a/lib/src/localization/languages/spanish_language.dart +++ b/lib/src/localization/languages/spanish_language.dart @@ -3,34 +3,56 @@ import '../language.dart'; class SpanishLanguage extends Language { SpanishLanguage() : super({ - Language.code.equalTo: "'{PropertyName}' debe ser igual a '{ComparisonValue}'.", - Language.code.greaterThan: "'{PropertyName}' debe ser mayor que '{ComparisonValue}'.", + Language.code.equalTo: + "'{PropertyName}' debe ser igual a '{ComparisonValue}'.", + Language.code.greaterThan: + "'{PropertyName}' debe ser mayor que '{ComparisonValue}'.", Language.code.isEmpty: "'{PropertyName}' debe estar vacío.", Language.code.isNotNull: "'{PropertyName}' no puede ser nulo.", Language.code.isNull: "'{PropertyName}' debe ser nulo.", - Language.code.lessThan: "'{PropertyName}' debe ser menor que '{ComparisonValue}'.", - Language.code.matchesPattern: "'{PropertyName}' no tiene el formato correcto.", - Language.code.max: "'{PropertyName}' debe ser menor o igual a {MaxValue}. Has ingresado {PropertyValue}.", - Language.code.maxLength: "El tamaño de '{PropertyName}' debe ser de {MaxLength} caracteres o menos. Has ingresado {TotalLength} caracteres.", - Language.code.min: "'{PropertyName}' debe ser mayor o igual a {MinValue}. Has ingresado {PropertyValue}.", - Language.code.minLength: "El tamaño de '{PropertyName}' debe ser de al menos {MinLength} caracteres. Has ingresado {TotalLength} caracteres.", - Language.code.mustHaveLowercase: "'{PropertyName}' debe tener al menos una letra minúscula.", - Language.code.mustHaveNumber: "'{PropertyName}' debe tener al menos un dígito ('0'-'9').", - Language.code.mustHaveSpecialCharacter: "'{PropertyName}' debe tener al menos un carácter no alfanumérico.", - Language.code.mustHaveUppercase: "'{PropertyName}' debe tener al menos una letra mayúscula.", + Language.code.lessThan: + "'{PropertyName}' debe ser menor que '{ComparisonValue}'.", + Language.code.matchesPattern: + "'{PropertyName}' no tiene el formato correcto.", + Language.code.max: + "'{PropertyName}' debe ser menor o igual a {MaxValue}. Has ingresado {PropertyValue}.", + Language.code.maxLength: + "El tamaño de '{PropertyName}' debe ser de {MaxLength} caracteres o menos. Has ingresado {TotalLength} caracteres.", + Language.code.min: + "'{PropertyName}' debe ser mayor o igual a {MinValue}. Has ingresado {PropertyValue}.", + Language.code.minLength: + "El tamaño de '{PropertyName}' debe ser de al menos {MinLength} caracteres. Has ingresado {TotalLength} caracteres.", + Language.code.mustHaveLowercase: + "'{PropertyName}' debe tener al menos una letra minúscula.", + Language.code.mustHaveNumber: + "'{PropertyName}' debe tener al menos un dígito ('0'-'9').", + Language.code.mustHaveSpecialCharacter: + "'{PropertyName}' debe tener al menos un carácter no alfanumérico.", + Language.code.mustHaveUppercase: + "'{PropertyName}' debe tener al menos una letra mayúscula.", Language.code.notEmpty: "'{PropertyName}' no puede estar vacío.", - Language.code.notEqualTo: "'{PropertyName}' no puede ser igual a '{ComparisonValue}'.", - Language.code.range: "'{PropertyName}' debe estar entre {From} y {To}. Has ingresado {PropertyValue}.", + Language.code.notEqualTo: + "'{PropertyName}' no puede ser igual a '{ComparisonValue}'.", + Language.code.range: + "'{PropertyName}' debe estar entre {From} y {To}. Has ingresado {PropertyValue}.", Language.code.validCEP: "'{PropertyName}' no es un CEP válido.", Language.code.validCPF: "'{PropertyName}' no es un CPF válido.", Language.code.validCNPJ: "'{PropertyName}' no es un CNPJ válido.", - Language.code.validCreditCard: "'{PropertyName}' no es un número de tarjeta de crédito válido.", - Language.code.validEmail: "'{PropertyName}' no es una dirección de correo electrónico válida.", - Language.code.greaterThanOrEqualToDateTime: "'{PropertyName}' debe ser mayor o igual a la fecha '{ComparisonValue}'.", - Language.code.greaterThanDatetime: "'{PropertyName}' debe ser mayor que la fecha '{ComparisonValue}'.", - Language.code.lessThanOrEqualToDateTime: "'{PropertyName}' debe ser menor o igual a la fecha '{ComparisonValue}'.", - Language.code.lessThanDateTime: "'{PropertyName}' debe ser menor que la fecha '{ComparisonValue}'.", - Language.code.inclusiveBetweenDatetime: "'{PropertyName}' debe ser mayor o igual a la fecha '{StartValue}' y menor o igual a la fecha '{EndValue}'.", - Language.code.exclusiveBetweenDatetime: "'{PropertyName}' debe ser mayor que la fecha '{StartValue}' y menor que la fecha '{EndValue}'." + Language.code.validCreditCard: + "'{PropertyName}' no es un número de tarjeta de crédito válido.", + Language.code.validEmail: + "'{PropertyName}' no es una dirección de correo electrónico válida.", + Language.code.greaterThanOrEqualToDateTime: + "'{PropertyName}' debe ser mayor o igual a la fecha '{ComparisonValue}'.", + Language.code.greaterThanDatetime: + "'{PropertyName}' debe ser mayor que la fecha '{ComparisonValue}'.", + Language.code.lessThanOrEqualToDateTime: + "'{PropertyName}' debe ser menor o igual a la fecha '{ComparisonValue}'.", + Language.code.lessThanDateTime: + "'{PropertyName}' debe ser menor que la fecha '{ComparisonValue}'.", + Language.code.inclusiveBetweenDatetime: + "'{PropertyName}' debe ser mayor o igual a la fecha '{StartValue}' y menor o igual a la fecha '{EndValue}'.", + Language.code.exclusiveBetweenDatetime: + "'{PropertyName}' debe ser mayor que la fecha '{StartValue}' y menor que la fecha '{EndValue}'." }); } diff --git a/lib/src/lucid_validation_builder.dart b/lib/src/lucid_validation_builder.dart index 32ca8b7..de117c2 100644 --- a/lib/src/lucid_validation_builder.dart +++ b/lib/src/lucid_validation_builder.dart @@ -51,6 +51,7 @@ typedef SimpleValidationBuilder = LucidValidationBuilder; abstract class LucidValidationBuilder { final String key; + final String label; final TProp Function(Entity entity) _selector; final List> _rules = []; var _mode = CascadeMode.continueExecution; @@ -61,7 +62,7 @@ abstract class LucidValidationBuilder { /// Creates a [LucidValidationBuilder] instance with an optional [key]. /// /// The [key] can be used to identify this specific validation in a larger validation context. - LucidValidationBuilder(this.key, this._selector); + LucidValidationBuilder(this.key, this.label, this._selector); String? Function([String?]) nestedByField(Entity entity, String key) { if (_nestedValidator == null) { @@ -83,7 +84,8 @@ abstract class LucidValidationBuilder { /// final builder = LucidValidationBuilder(key: 'username'); /// builder.must((username) => username.isNotEmpty, 'Username cannot be empty'); /// ``` - LucidValidationBuilder must(bool Function(TProp value) validator, String message, String code) { + LucidValidationBuilder must( + bool Function(TProp value) validator, String message, String code) { ValidationException? callback(value, entity) { if (validator(value)) { return null; @@ -223,7 +225,8 @@ abstract class LucidValidationBuilder { /// In the example above, the phone number validation rules are only applied if the user's `requiresPhoneNumber` /// property is true. If the condition is false, the phone number field will be considered valid, and the /// associated rules will not be executed. - LucidValidationBuilder when(bool Function(Entity entity) condition) { + LucidValidationBuilder when( + bool Function(Entity entity) condition) { _condition = condition; return this; } @@ -238,7 +241,8 @@ abstract class LucidValidationBuilder { final exceptions = []; if (_nestedValidator != null) { - final nestedExceptions = _nestedValidator!.validate(_selector(entity)).exceptions; + final nestedExceptions = + _nestedValidator!.validate(_selector(entity)).exceptions; exceptions.addAll(nestedExceptions); } else { for (var rule in _rules) { diff --git a/lib/src/lucid_validator.dart b/lib/src/lucid_validator.dart index adf597d..928fcf9 100644 --- a/lib/src/lucid_validator.dart +++ b/lib/src/lucid_validator.dart @@ -18,8 +18,11 @@ abstract class LucidValidator { /// final validator = UserValidation(); /// validator.ruleFor((user) => user.email).validEmail(); /// ``` - LucidValidationBuilder ruleFor(TProp Function(E entity) selector, {required String key}) { - final builder = _LucidValidationBuilder(key, selector); + LucidValidationBuilder ruleFor( + TProp Function(E entity) selector, + {required String key, + String label = ''}) { + final builder = _LucidValidationBuilder(key, label, selector); _builders.add(builder); return builder; @@ -86,7 +89,8 @@ abstract class LucidValidator { /// } /// ``` ValidationResult validate(E entity) { - final exceptions = _builders.fold([], (previousErrors, builder) { + final exceptions = + _builders.fold([], (previousErrors, builder) { return previousErrors..addAll(builder.executeRules(entity)); }); @@ -97,6 +101,7 @@ abstract class LucidValidator { } } -class _LucidValidationBuilder extends LucidValidationBuilder { - _LucidValidationBuilder(super.key, super.selector); +class _LucidValidationBuilder + extends LucidValidationBuilder { + _LucidValidationBuilder(super.key, super.label, super.selector); } diff --git a/lib/src/validations/equal_validation.dart b/lib/src/validations/equal_validation.dart index 61bcbf8..9abd21d 100644 --- a/lib/src/validations/equal_validation.dart +++ b/lib/src/validations/equal_validation.dart @@ -39,7 +39,7 @@ extension EqualValidation on LucidValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'ComparisonValue': '$comparison', }, defaultMessage: message, diff --git a/lib/src/validations/exclusive_between_datetime_validation.dart b/lib/src/validations/exclusive_between_datetime_validation.dart index bdc0025..f1c42d9 100644 --- a/lib/src/validations/exclusive_between_datetime_validation.dart +++ b/lib/src/validations/exclusive_between_datetime_validation.dart @@ -4,7 +4,8 @@ part of 'validations.dart'; /// /// This extension adds an `inclusiveBetween` method that can be used to /// ensure that a date is exclusive between two specified dates. -extension ExclusiveBetweenDatetimeValidation on SimpleValidationBuilder { +extension ExclusiveBetweenDatetimeValidation + on SimpleValidationBuilder { /// Adds a validation rule that checks if the [DateTime] is greater than [comparison]. /// /// [start] is the date and time value must be greater than. @@ -39,7 +40,7 @@ extension ExclusiveBetweenDatetimeValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'ComparisonValue': comparison.toString(), }, defaultMessage: message, diff --git a/lib/src/validations/greater_than_or_equal_to_datetime_validation.dart b/lib/src/validations/greater_than_or_equal_to_datetime_validation.dart index 34ec37c..6832e74 100644 --- a/lib/src/validations/greater_than_or_equal_to_datetime_validation.dart +++ b/lib/src/validations/greater_than_or_equal_to_datetime_validation.dart @@ -4,7 +4,8 @@ part of 'validations.dart'; /// /// This extension adds a `greaterThanOrEqualTo` method that can be used to ensure that /// a date is greater than or equal to a specified date. -extension GreaterThanOrEqualToDateTimeValidation on SimpleValidationBuilder { +extension GreaterThanOrEqualToDateTimeValidation + on SimpleValidationBuilder { /// Adds a validation rule that checks if the [DateTime] is greater than [comparison]. /// /// [comparison] is the date and time value must be greater than or equal. @@ -30,13 +31,14 @@ extension GreaterThanOrEqualToDateTimeValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'ComparisonValue': '$minValue', }, defaultMessage: message, diff --git a/lib/src/validations/inclusive_between_datetime_validation.dart b/lib/src/validations/inclusive_between_datetime_validation.dart index 8561566..e93f267 100644 --- a/lib/src/validations/inclusive_between_datetime_validation.dart +++ b/lib/src/validations/inclusive_between_datetime_validation.dart @@ -4,7 +4,8 @@ part of 'validations.dart'; /// /// This extension adds an `inclusiveBetween` method that can be used to /// ensure that a date is inclusive between two specified dates. -extension InclusiveBetweenDatetimeValidation on SimpleValidationBuilder { +extension InclusiveBetweenDatetimeValidation + on SimpleValidationBuilder { /// Adds a validation rule that checks if the [DateTime] is greater than [comparison]. /// /// [start] is the date and time value must be greater than or equal to. @@ -33,13 +34,15 @@ extension InclusiveBetweenDatetimeValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/is_not_null_validation.dart b/lib/src/validations/is_not_null_validation.dart index 305616f..b7fbf9b 100644 --- a/lib/src/validations/is_not_null_validation.dart +++ b/lib/src/validations/is_not_null_validation.dart @@ -31,7 +31,7 @@ extension IsNotNullValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/is_null_validation.dart b/lib/src/validations/is_null_validation.dart index 6deda78..8dd3e62 100644 --- a/lib/src/validations/is_null_validation.dart +++ b/lib/src/validations/is_null_validation.dart @@ -31,7 +31,7 @@ extension IsNullValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/less_than_datetime_validation.dart b/lib/src/validations/less_than_datetime_validation.dart index b270072..b056f31 100644 --- a/lib/src/validations/less_than_datetime_validation.dart +++ b/lib/src/validations/less_than_datetime_validation.dart @@ -36,7 +36,7 @@ extension LessThanDatetimeValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'ComparisonValue': comparison.toString(), }, defaultMessage: message, diff --git a/lib/src/validations/less_than_or_equal_to_datetime_validation.dart b/lib/src/validations/less_than_or_equal_to_datetime_validation.dart index dfc8a74..123e598 100644 --- a/lib/src/validations/less_than_or_equal_to_datetime_validation.dart +++ b/lib/src/validations/less_than_or_equal_to_datetime_validation.dart @@ -4,7 +4,8 @@ part of 'validations.dart'; /// /// This extension adds a `lessThanOrEqualTo` method that can be used to ensure that /// a date is less than or equal to a specified date. -extension LessThanOrEqualToDatetimeValidation on SimpleValidationBuilder { +extension LessThanOrEqualToDatetimeValidation + on SimpleValidationBuilder { /// Adds a validation rule that checks if the [DateTime] is greater than [comparison]. /// /// [comparison] is the date and time value must be less than or equal to. @@ -30,13 +31,14 @@ extension LessThanOrEqualToDatetimeValidation on SimpleValidationBuilder { /// - **{PropertyName}**: The name of the property. /// - **{ComparisonValue}**: The value to compare against. /// - SimpleValidationBuilder lessThan(num maxValue, {String? message, String? code}) { + SimpleValidationBuilder lessThan(num maxValue, + {String? message, String? code}) { return use( (value, entity) { if (value < maxValue) return null; @@ -33,7 +34,7 @@ extension LessThanValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'ComparisonValue': '$maxValue', }, defaultMessage: message, diff --git a/lib/src/validations/matches_pattern_validation.dart b/lib/src/validations/matches_pattern_validation.dart index f347e36..ce60e7b 100644 --- a/lib/src/validations/matches_pattern_validation.dart +++ b/lib/src/validations/matches_pattern_validation.dart @@ -23,7 +23,8 @@ extension MatchesPatternValidation on SimpleValidationBuilder { /// String format args: /// - **{PropertyName}**: The name of the property. /// - SimpleValidationBuilder matchesPattern(String pattern, {String? message, String? code}) { + SimpleValidationBuilder matchesPattern(String pattern, + {String? message, String? code}) { return use( (value, entity) { final isValid = RegExp(pattern).hasMatch(value); @@ -34,7 +35,7 @@ extension MatchesPatternValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/max_length_validation.dart b/lib/src/validations/max_length_validation.dart index 9513fb7..e93adec 100644 --- a/lib/src/validations/max_length_validation.dart +++ b/lib/src/validations/max_length_validation.dart @@ -25,7 +25,8 @@ extension MaxLengthValidation on SimpleValidationBuilder { /// - **{MaxLength}**: The value to compare against. /// - **{TotalLength}**: total characters entered. /// - SimpleValidationBuilder maxLength(int num, {String? message, String? code}) { + SimpleValidationBuilder maxLength(int num, + {String? message, String? code}) { return use( (value, entity) { if (value.length <= num) return null; @@ -34,7 +35,7 @@ extension MaxLengthValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'MaxLength': '$num', 'TotalLength': '${value.length}', }, diff --git a/lib/src/validations/max_validation.dart b/lib/src/validations/max_validation.dart index b629090..698107d 100644 --- a/lib/src/validations/max_validation.dart +++ b/lib/src/validations/max_validation.dart @@ -34,7 +34,7 @@ extension MaxValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'MaxValue': '$num', 'PropertyValue': '$value', }, diff --git a/lib/src/validations/min_length_validation.dart b/lib/src/validations/min_length_validation.dart index 0a732c5..9157751 100644 --- a/lib/src/validations/min_length_validation.dart +++ b/lib/src/validations/min_length_validation.dart @@ -24,7 +24,8 @@ extension MinLengthValidation on SimpleValidationBuilder { /// - **{PropertyName}**: The name of the property. /// - **{MinLength}**: The value to compare against. /// - **{TotalLength}**: total characters entered. - SimpleValidationBuilder minLength(int num, {String? message, String? code}) { + SimpleValidationBuilder minLength(int num, + {String? message, String? code}) { return use( (value, entity) { if (value.length >= num) return null; @@ -33,7 +34,7 @@ extension MinLengthValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'MinLength': '$num', 'TotalLength': '${value.length}', }, diff --git a/lib/src/validations/min_validation.dart b/lib/src/validations/min_validation.dart index 29302ff..94d52a8 100644 --- a/lib/src/validations/min_validation.dart +++ b/lib/src/validations/min_validation.dart @@ -34,7 +34,7 @@ extension MinValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'MinValue': '$num', 'PropertyValue': '$value', }, diff --git a/lib/src/validations/must_have_lowercase_validation.dart b/lib/src/validations/must_have_lowercase_validation.dart index d118b6d..a8bbb65 100644 --- a/lib/src/validations/must_have_lowercase_validation.dart +++ b/lib/src/validations/must_have_lowercase_validation.dart @@ -23,7 +23,8 @@ extension MustHaveLowercaseValidation on SimpleValidationBuilder { /// - **{PropertyName}**: The name of the property. /// /// '{PropertyName}' must have at least one lowercase letter. - SimpleValidationBuilder mustHaveLowercase({String? message, String? code}) { + SimpleValidationBuilder mustHaveLowercase( + {String? message, String? code}) { return use( (value, entity) { final isValid = RegExp(r'[a-z]').hasMatch(value); @@ -33,7 +34,7 @@ extension MustHaveLowercaseValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/must_have_number_validation.dart b/lib/src/validations/must_have_number_validation.dart index b740c44..38567e5 100644 --- a/lib/src/validations/must_have_number_validation.dart +++ b/lib/src/validations/must_have_number_validation.dart @@ -22,7 +22,8 @@ extension MustHaveNumbersValidation on SimpleValidationBuilder { /// String format args: /// - **{PropertyName}**: The name of the property. /// - SimpleValidationBuilder mustHaveNumber({String? message, String? code}) { + SimpleValidationBuilder mustHaveNumber( + {String? message, String? code}) { return use( (value, entity) { final isValid = RegExp(r'[0-9]').hasMatch(value); @@ -32,7 +33,7 @@ extension MustHaveNumbersValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/must_have_special_character_validation.dart b/lib/src/validations/must_have_special_character_validation.dart index a601a5c..fc39738 100644 --- a/lib/src/validations/must_have_special_character_validation.dart +++ b/lib/src/validations/must_have_special_character_validation.dart @@ -4,7 +4,8 @@ part of 'validations.dart'; /// /// This extension adds a `mustHaveSpecialCharacter` method that can be used to ensure that a string /// contains at least one special character. -extension MustHaveSpecialCharacterValidation on SimpleValidationBuilder { +extension MustHaveSpecialCharacterValidation + on SimpleValidationBuilder { /// Adds a validation rule that checks if the [String] contains at least one special character. /// /// [message] is the error message returned if the validation fails. Defaults to "Must contain at least one special character". @@ -22,7 +23,8 @@ extension MustHaveSpecialCharacterValidation on SimpleValidationBuilder /// String format args: /// - **{PropertyName}**: The name of the property. /// - SimpleValidationBuilder mustHaveSpecialCharacter({String? message, String? code}) { + SimpleValidationBuilder mustHaveSpecialCharacter( + {String? message, String? code}) { return use( (value, entity) { final isValid = RegExp(r'[!@#\$%\^&\*(),.?":{}|<>]').hasMatch(value); @@ -32,7 +34,7 @@ extension MustHaveSpecialCharacterValidation on SimpleValidationBuilder final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/must_have_uppercase_validation.dart b/lib/src/validations/must_have_uppercase_validation.dart index 7e49464..e3fbf77 100644 --- a/lib/src/validations/must_have_uppercase_validation.dart +++ b/lib/src/validations/must_have_uppercase_validation.dart @@ -22,7 +22,8 @@ extension MustHaveUppercaseValidation on SimpleValidationBuilder { /// String format args: /// - **{PropertyName}**: The name of the property. /// - SimpleValidationBuilder mustHaveUppercase({String? message, String? code}) { + SimpleValidationBuilder mustHaveUppercase( + {String? message, String? code}) { return use( (value, entity) { final isValid = RegExp(r'[A-Z]').hasMatch(value); @@ -32,7 +33,7 @@ extension MustHaveUppercaseValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/not_empty_validation.dart b/lib/src/validations/not_empty_validation.dart index c3dd7b2..bc2d35d 100644 --- a/lib/src/validations/not_empty_validation.dart +++ b/lib/src/validations/not_empty_validation.dart @@ -31,7 +31,7 @@ extension NotEmptyValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/not_equal_validation.dart b/lib/src/validations/not_equal_validation.dart index b5b3b12..b3bbac8 100644 --- a/lib/src/validations/not_equal_validation.dart +++ b/lib/src/validations/not_equal_validation.dart @@ -24,7 +24,8 @@ extension NotEqualValidation on LucidValidationBuilder { /// - **{PropertyName}**: The name of the property. /// - **{ComparisonValue}**: The value to compare against. /// - LucidValidationBuilder notEqualTo(T Function(E entity) predicate, {String? message, String? code}) { + LucidValidationBuilder notEqualTo(T Function(E entity) predicate, + {String? message, String? code}) { return use( (value, entity) { final comparison = predicate(entity); @@ -34,7 +35,7 @@ extension NotEqualValidation on LucidValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'ComparisonValue': '$comparison', }, defaultMessage: message, diff --git a/lib/src/validations/range_validation.dart b/lib/src/validations/range_validation.dart index e673f6c..7afa1e9 100644 --- a/lib/src/validations/range_validation.dart +++ b/lib/src/validations/range_validation.dart @@ -26,7 +26,8 @@ extension RangeValidation on SimpleValidationBuilder { /// - **{To}**: The maximum value of the range. /// - **{PropertyValue}**: The value of the property. /// - SimpleValidationBuilder range(num min, num max, {String? message, String? code}) { + SimpleValidationBuilder range(num min, num max, + {String? message, String? code}) { return use( (value, entity) { if (value >= min && value <= max) return null; @@ -35,7 +36,7 @@ extension RangeValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, 'From': '$min', 'To': '$max', 'PropertyValue': '$value', diff --git a/lib/src/validations/valid_cep_validation.dart b/lib/src/validations/valid_cep_validation.dart index 8d41849..6885040 100644 --- a/lib/src/validations/valid_cep_validation.dart +++ b/lib/src/validations/valid_cep_validation.dart @@ -29,7 +29,7 @@ extension ValidCEPValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/valid_cnpj_validation.dart b/lib/src/validations/valid_cnpj_validation.dart index 600eada..4828e64 100644 --- a/lib/src/validations/valid_cnpj_validation.dart +++ b/lib/src/validations/valid_cnpj_validation.dart @@ -30,7 +30,7 @@ extension ValidCnpjValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/valid_cpf_validation.dart b/lib/src/validations/valid_cpf_validation.dart index 65fa0b5..a643b12 100644 --- a/lib/src/validations/valid_cpf_validation.dart +++ b/lib/src/validations/valid_cpf_validation.dart @@ -30,7 +30,7 @@ extension ValidCPFValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/valid_creditcard_validation.dart b/lib/src/validations/valid_creditcard_validation.dart index 4bb5b94..55a5398 100644 --- a/lib/src/validations/valid_creditcard_validation.dart +++ b/lib/src/validations/valid_creditcard_validation.dart @@ -21,7 +21,8 @@ extension ValidCreditCardValidation on SimpleValidationBuilder { /// String format args: /// - **{PropertyName}**: The name of the property. /// - SimpleValidationBuilder validCreditCard({String? message, String? code}) { + SimpleValidationBuilder validCreditCard( + {String? message, String? code}) { return use((value, entity) { if (_validateCreditCard(value)) return null; @@ -29,7 +30,7 @@ extension ValidCreditCardValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/lib/src/validations/valid_email_validation.dart b/lib/src/validations/valid_email_validation.dart index 4bad4b0..f064c1a 100644 --- a/lib/src/validations/valid_email_validation.dart +++ b/lib/src/validations/valid_email_validation.dart @@ -32,7 +32,7 @@ extension ValidEmailValidation on SimpleValidationBuilder { final currentMessage = LucidValidation.global.languageManager.translate( currentCode, parameters: { - 'PropertyName': key, + 'PropertyName': label.isNotEmpty ? label : key, }, defaultMessage: message, ); diff --git a/pubspec.yaml b/pubspec.yaml index e173fc9..2578a59 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: "A Dart/Flutter package for building strongly typed validation rule repository: https://github.com/Flutterando/lucid_validation homepage: https://pub.dev/documentation/lucid_validation/latest/ -version: 1.0.1 +version: 1.1.0 environment: sdk: ">=3.0.0 <4.0.0" diff --git a/test/byfield_validation_test.dart b/test/byfield_validation_test.dart index 8560041..4afb74c 100644 --- a/test/byfield_validation_test.dart +++ b/test/byfield_validation_test.dart @@ -31,16 +31,26 @@ void main() { group('nested byfield normal', () { final flagValidator = TestLucidValidator(); - flagValidator.ruleFor((flag) => flag.value, key: 'value').equalTo((entity) => true); + flagValidator + .ruleFor((flag) => flag.value, key: 'value') + .equalTo((entity) => true); final categoryValidator = TestLucidValidator(); - categoryValidator.ruleFor((category) => category.name, key: 'name').notEmpty(); - categoryValidator.ruleFor((category) => category.flag, key: 'flag').setValidator(flagValidator); + categoryValidator + .ruleFor((category) => category.name, key: 'name') + .notEmpty(); + categoryValidator + .ruleFor((category) => category.flag, key: 'flag') + .setValidator(flagValidator); final productValidator = TestLucidValidator(); productValidator.ruleFor((product) => product.name, key: 'name').notEmpty(); - productValidator.ruleFor((product) => product.price, key: 'price').greaterThan(0); - productValidator.ruleFor((product) => product.category, key: 'category').setValidator(categoryValidator); + productValidator + .ruleFor((product) => product.price, key: 'price') + .greaterThan(0); + productValidator + .ruleFor((product) => product.category, key: 'category') + .setValidator(categoryValidator); final product = ProductModel(); @@ -60,22 +70,26 @@ void main() { }); test('categoryNameValidator', () { - final categoryNameValidatorFn = productValidator.byField(product, 'category.name'); + final categoryNameValidatorFn = + productValidator.byField(product, 'category.name'); expect(categoryNameValidatorFn(), isNotNull); }); test('flagValidator', () { - final flagValidatorFn = productValidator.byField(product, 'category.flag'); + final flagValidatorFn = + productValidator.byField(product, 'category.flag'); expect(flagValidatorFn(), isNotNull); }); test('flagValueValidator', () { - final flagValueValidatorFn = productValidator.byField(product, 'category.flag.value'); + final flagValueValidatorFn = + productValidator.byField(product, 'category.flag.value'); expect(flagValueValidatorFn(), isNotNull); }); test('must return null if not found key', () { - final flagValueValidatorFn = productValidator.byField(product, 'category.flag.notExists'); + final flagValueValidatorFn = + productValidator.byField(product, 'category.flag.notExists'); expect(flagValueValidatorFn(), null); }); @@ -88,9 +102,12 @@ void main() { final nameValidator = productValidator.byField(product, 'name'); final priceValidator = productValidator.byField(product, 'price'); final categoryValidatorFn = productValidator.byField(product, 'category'); - final categoryNameValidatorFn = productValidator.byField(product, 'category.name'); - final flagValidatorFn = productValidator.byField(product, 'category.flag'); - final flagValueValidatorFn = productValidator.byField(product, 'category.flag.value'); + final categoryNameValidatorFn = + productValidator.byField(product, 'category.name'); + final flagValidatorFn = + productValidator.byField(product, 'category.flag'); + final flagValueValidatorFn = + productValidator.byField(product, 'category.flag.value'); expect(nameValidator(), null); expect(priceValidator(), null); diff --git a/test/lucid_validation_test.dart b/test/lucid_validation_test.dart index ce542ff..86bab04 100644 --- a/test/lucid_validation_test.dart +++ b/test/lucid_validation_test.dart @@ -3,7 +3,9 @@ import 'package:test/test.dart'; import 'mocks/mocks.dart'; void main() { - test('when validating [UserEntityMock] should return a list of error messages for the email field', () { + test( + 'when validating [UserEntityMock] should return a list of error messages for the email field', + () { final validator = UserValidator(); final userEntity = UserModel() ..age = 18 @@ -17,7 +19,9 @@ void main() { expect(exceptions.length, 4); }); - test('when validating [UserModel] should return a list of error messages for the password field', () { + test( + 'when validating [UserModel] should return a list of error messages for the password field', + () { final validator = UserValidator(); final userEntity = UserModel() ..age = 18 @@ -31,7 +35,9 @@ void main() { expect(exceptions.length, 8); }); - test('when validating [UserModel] should return a list of error messages for the age field', () { + test( + 'when validating [UserModel] should return a list of error messages for the age field', + () { final validator = UserValidator(); final userEntity = UserModel() ..age = 15 @@ -45,7 +51,9 @@ void main() { expect(exceptions.length, 3); }); - test('when validating [UserModel] should return a list of error messages for the phone field', () { + test( + 'when validating [UserModel] should return a list of error messages for the phone field', + () { final validator = UserValidator(); final userEntity = UserModel() @@ -60,7 +68,9 @@ void main() { expect(exceptions.length, 3); }); - test('when validating [UserModel] should return a list of error messages for all fields', () { + test( + 'when validating [UserModel] should return a list of error messages for all fields', + () { final validator = UserValidator(); final userEntity = UserModel()..age = 15; diff --git a/test/mocks/mocks.dart b/test/mocks/mocks.dart index 37a6961..ba9877e 100644 --- a/test/mocks/mocks.dart +++ b/test/mocks/mocks.dart @@ -42,7 +42,8 @@ extension CustomValidPhoneValidator on LucidValidationBuilder { } } -extension CustomValidPasswordValidator on LucidValidationBuilder { +extension CustomValidPasswordValidator + on LucidValidationBuilder { LucidValidationBuilder customValidPassword() { return notEmpty() // .minLength(5, message: 'Must be at least 8 characters long') @@ -85,10 +86,13 @@ class CredentialsRegisterValidator extends LucidValidator { ruleFor((credentials) => credentials.password, key: 'password') // .customValidPassword() - .equalTo((entity) => entity.confirmPassword, message: 'Must be equal to confirmPassword'); + .equalTo((entity) => entity.confirmPassword, + message: 'Must be equal to confirmPassword'); - ruleFor((credentials) => credentials.confirmPassword, key: 'confirmPassword') // - .equalTo((entity) => entity.password, message: 'Must be equal to password'); + ruleFor((credentials) => credentials.confirmPassword, + key: 'confirmPassword') // + .equalTo((entity) => entity.password, + message: 'Must be equal to password'); } } diff --git a/test/src/validations/equal_validation_test.dart b/test/src/validations/equal_validation_test.dart index 62e0b35..45f5ae7 100644 --- a/test/src/validations/equal_validation_test.dart +++ b/test/src/validations/equal_validation_test.dart @@ -26,7 +26,9 @@ void main() { final validator = TestLucidValidator(); validator .ruleFor((user) => user.confirmPassword, key: 'confirmPassword') // - .equalTo((user) => user.password, message: "Campo '{PropertyName}' deve ser igual ao campo '{ComparisonValue}'."); + .equalTo((user) => user.password, + message: + "Campo '{PropertyName}' deve ser igual ao campo '{ComparisonValue}'."); final user = UserModel() ..password = 'password' @@ -37,6 +39,7 @@ void main() { expect(result.exceptions.length, 1); final error = result.exceptions.first; - expect(error.message, r"Campo 'confirmPassword' deve ser igual ao campo 'password'."); + expect(error.message, + r"Campo 'confirmPassword' deve ser igual ao campo 'password'."); }); } diff --git a/test/src/validations/exclusive_between_datetime_validation_test.dart b/test/src/validations/exclusive_between_datetime_validation_test.dart index 8ef0616..2927200 100644 --- a/test/src/validations/exclusive_between_datetime_validation_test.dart +++ b/test/src/validations/exclusive_between_datetime_validation_test.dart @@ -4,7 +4,9 @@ import 'package:test/test.dart'; import '../../mocks/mocks.dart'; void main() { - test('should fail exclusive between validation when the event date is exactly on the start boundary', () { + test( + 'should fail exclusive between validation when the event date is exactly on the start boundary', + () { final validator = TestLucidValidator(); final now = DateTime.now(); final tomorrow = now.add(Duration(days: 1)); @@ -20,10 +22,13 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'dateEvent' must be less than the '${tomorrow.toString()}' date and less than the '${afterTomorrow.toString()}' date."); + expect(result.exceptions.first.message, + "'dateEvent' must be greater than the '${tomorrow.toString()}' date and less than the '${afterTomorrow.toString()}' date."); }); - test('should fail exclusive between validation when the event date is exactly on the end boundary', () { + test( + 'should fail exclusive between validation when the event date is exactly on the end boundary', + () { final validator = TestLucidValidator(); final now = DateTime.now(); final tomorrow = now.add(Duration(days: 1)); @@ -39,10 +44,13 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'dateEvent' must be less than the '${tomorrow.toString()}' date and less than the '${afterTomorrow.toString()}' date."); + expect(result.exceptions.first.message, + "'dateEvent' must be greater than the '${tomorrow.toString()}' date and less than the '${afterTomorrow.toString()}' date."); }); - test('should fail exclusive between validation when the event date is exactly on the end boundary', () { + test( + 'should fail exclusive between validation when the event date is exactly on the end boundary', + () { final validator = TestLucidValidator(); final now = DateTime.now(); final tomorrow = now.add(Duration(days: 1)); diff --git a/test/src/validations/greater_than_datetime_validation_test.dart b/test/src/validations/greater_than_datetime_validation_test.dart index 6972fc3..18acd60 100644 --- a/test/src/validations/greater_than_datetime_validation_test.dart +++ b/test/src/validations/greater_than_datetime_validation_test.dart @@ -18,6 +18,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'start' must be greater than date '${now.toString()}'."); + expect(result.exceptions.first.message, + "'start' must be greater than date '${now.toString()}'."); }); } diff --git a/test/src/validations/greater_than_or_equal_to_datetime_validation_test.dart b/test/src/validations/greater_than_or_equal_to_datetime_validation_test.dart index 6c83f08..e1005b7 100644 --- a/test/src/validations/greater_than_or_equal_to_datetime_validation_test.dart +++ b/test/src/validations/greater_than_or_equal_to_datetime_validation_test.dart @@ -18,7 +18,8 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'start' must be greater than or equal to date '${now.toString()}'."); + expect(result.exceptions.first.message, + "'start' must be greater than or equal to date '${now.toString()}'."); }); test('greater than or equal to validation ...', () { diff --git a/test/src/validations/inclusive_between_datetime_validation_test.dart b/test/src/validations/inclusive_between_datetime_validation_test.dart index b607035..f58ed51 100644 --- a/test/src/validations/inclusive_between_datetime_validation_test.dart +++ b/test/src/validations/inclusive_between_datetime_validation_test.dart @@ -20,6 +20,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'dateEvent' must be less than the '${tomorrow.toString()}' date and less than the '${afterTomorrow.toString()}' date."); + expect(result.exceptions.first.message, + "'dateEvent' must be greater than or equal to '${tomorrow.toString()}' date and less than or equal to '${afterTomorrow.toString()}' date."); }); } diff --git a/test/src/validations/less_than_datetime_validation_test.dart b/test/src/validations/less_than_datetime_validation_test.dart index 4e6d6a8..0871321 100644 --- a/test/src/validations/less_than_datetime_validation_test.dart +++ b/test/src/validations/less_than_datetime_validation_test.dart @@ -19,6 +19,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'end' must be less than date '${now.toString()}'."); + expect(result.exceptions.first.message, + "'end' must be less than date '${now.toString()}'."); }); } diff --git a/test/src/validations/less_than_or_equal_to_datetime_validation_test.dart b/test/src/validations/less_than_or_equal_to_datetime_validation_test.dart index 227ed06..caa035b 100644 --- a/test/src/validations/less_than_or_equal_to_datetime_validation_test.dart +++ b/test/src/validations/less_than_or_equal_to_datetime_validation_test.dart @@ -19,7 +19,8 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'end' must be less than or equal to date '${now.toString()}'."); + expect(result.exceptions.first.message, + "'end' must be less than or equal to date '${now.toString()}'."); }); test('less than or equal to validation ...', () { diff --git a/test/src/validations/matches_pattern_validation_test.dart b/test/src/validations/matches_pattern_validation_test.dart index 55ce9d4..f0ef0aa 100644 --- a/test/src/validations/matches_pattern_validation_test.dart +++ b/test/src/validations/matches_pattern_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'email' is not in the correct format."); + expect(result.exceptions.first.message, + "'email' is not in the correct format."); }); } diff --git a/test/src/validations/max_length_validation_test.dart b/test/src/validations/max_length_validation_test.dart index 6013105..8568d6b 100644 --- a/test/src/validations/max_length_validation_test.dart +++ b/test/src/validations/max_length_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "The length of 'password' must be 8 characters or fewer. You entered 9 characters."); + expect(result.exceptions.first.message, + "The length of 'password' must be 8 characters or fewer. You entered 9 characters."); }); } diff --git a/test/src/validations/max_validation_test.dart b/test/src/validations/max_validation_test.dart index d36f9fd..85fa14c 100644 --- a/test/src/validations/max_validation_test.dart +++ b/test/src/validations/max_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'age' must be less than or equal to 18. You entered 20."); + expect(result.exceptions.first.message, + "'age' must be less than or equal to 18. You entered 20."); }); } diff --git a/test/src/validations/min_length_validation_test.dart b/test/src/validations/min_length_validation_test.dart index 1dca1ac..d5ffd19 100644 --- a/test/src/validations/min_length_validation_test.dart +++ b/test/src/validations/min_length_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "The length of 'password' must be at least 8 characters. You entered 6 characters."); + expect(result.exceptions.first.message, + "The length of 'password' must be at least 8 characters. You entered 6 characters."); }); } diff --git a/test/src/validations/min_validation_test.dart b/test/src/validations/min_validation_test.dart index 0b5ad42..7eaf8a2 100644 --- a/test/src/validations/min_validation_test.dart +++ b/test/src/validations/min_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'age' must be greater than or equal to 18. You entered 17."); + expect(result.exceptions.first.message, + "'age' must be greater than or equal to 18. You entered 17."); }); } diff --git a/test/src/validations/must_have_lowercase_validation_test.dart b/test/src/validations/must_have_lowercase_validation_test.dart index 7376162..c2544e9 100644 --- a/test/src/validations/must_have_lowercase_validation_test.dart +++ b/test/src/validations/must_have_lowercase_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'password' must have at least one lowercase letter."); + expect(result.exceptions.first.message, + "'password' must have at least one lowercase letter."); }); } diff --git a/test/src/validations/must_have_number_validation_test.dart b/test/src/validations/must_have_number_validation_test.dart index 461fdd8..780fba4 100644 --- a/test/src/validations/must_have_number_validation_test.dart +++ b/test/src/validations/must_have_number_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'password' must have at least one digit ('0'-'9')."); + expect(result.exceptions.first.message, + "'password' must have at least one digit ('0'-'9')."); }); } diff --git a/test/src/validations/must_have_special_character_validation_test.dart b/test/src/validations/must_have_special_character_validation_test.dart index 3b16cc4..8654f10 100644 --- a/test/src/validations/must_have_special_character_validation_test.dart +++ b/test/src/validations/must_have_special_character_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'password' must have at least one non-alphanumeric character."); + expect(result.exceptions.first.message, + "'password' must have at least one non-alphanumeric character."); }); } diff --git a/test/src/validations/must_have_uppercase_validation_test.dart b/test/src/validations/must_have_uppercase_validation_test.dart index 5f7c364..259ad4e 100644 --- a/test/src/validations/must_have_uppercase_validation_test.dart +++ b/test/src/validations/must_have_uppercase_validation_test.dart @@ -16,6 +16,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'password' must have at least one uppercase letter."); + expect(result.exceptions.first.message, + "'password' must have at least one uppercase letter."); }); } diff --git a/test/src/validations/not_equal_validation_test.dart b/test/src/validations/not_equal_validation_test.dart index 290b0fd..f81fef2 100644 --- a/test/src/validations/not_equal_validation_test.dart +++ b/test/src/validations/not_equal_validation_test.dart @@ -18,6 +18,7 @@ void main() { expect(result.isValid, false); expect(result.exceptions.length, 1); - expect(result.exceptions.first.message, "'confirmPassword' must not be equal to 'teste123'."); + expect(result.exceptions.first.message, + "'confirmPassword' must not be equal to 'teste123'."); }); } diff --git a/test/src/validations/valid_email_validation_test.dart b/test/src/validations/valid_email_validation_test.dart index c39aed6..627d174 100644 --- a/test/src/validations/valid_email_validation_test.dart +++ b/test/src/validations/valid_email_validation_test.dart @@ -8,7 +8,7 @@ void main() { final validator = TestLucidValidator(); validator - .ruleFor((e) => e.email, key: 'email') // + .ruleFor((e) => e.email, key: 'email', label: 'E-mail') // .validEmail(); final user = UserModel()..email = 'testtest.com'; @@ -21,6 +21,6 @@ void main() { final error = result.exceptions.first; - expect(error.message, "'email' is not a valid email address."); + expect(error.message, "'E-mail' is not a valid email address."); }); }