Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobaraujo7 committed Aug 27, 2024
2 parents 80d1be4 + 647cd96 commit 3131bc6
Show file tree
Hide file tree
Showing 54 changed files with 611 additions and 180 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ void main() {
if (result.isValid) {
print('User is valid');
} else {
print('Validation errors: \${result.errors.map((e) => e.message).join(', ')}');
print('Validation errors: \${result.exceptions.map((e) => e.message).join(', ')}');
}
}
```
Expand Down
2 changes: 1 addition & 1 deletion example/lib/presentation/register_page/register_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class _RegisterPageState extends State<RegisterPage> {
/// call to api passing the parameter loginParamDto
ScaffoldMessenger.of(context).showSnackBar(sucessSnackBar());
} else {
ScaffoldMessenger.of(context).showSnackBar(failureSnackBar(result.errors.first.message));
ScaffoldMessenger.of(context).showSnackBar(failureSnackBar(result.exceptions.first.message));
}
}

Expand Down
30 changes: 15 additions & 15 deletions lib/src/lucid_validation_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ enum CascadeMode {
/// Builder class used to define validation rules for a specific property type [TProp].
///
/// [TProp] represents the type of the property being validated.
typedef RuleFunc<Entity> = ValidationError? Function(Entity entity);
typedef RuleFunc<Entity> = ValidationException? Function(Entity entity);

typedef SimpleValidationBuilder<T> = LucidValidationBuilder<T, dynamic>;

Expand Down Expand Up @@ -84,11 +84,11 @@ abstract class LucidValidationBuilder<TProp, Entity> {
/// builder.must((username) => username.isNotEmpty, 'Username cannot be empty');
/// ```
LucidValidationBuilder<TProp, Entity> must(bool Function(TProp value) validator, String message, String code) {
ValidationError? callback(value, entity) {
ValidationException? callback(value, entity) {
if (validator(value)) {
return null;
}
return ValidationError(
return ValidationException(
message: message,
key: key,
code: code,
Expand Down Expand Up @@ -130,7 +130,7 @@ abstract class LucidValidationBuilder<TProp, Entity> {
return null;
}

return ValidationError(
return ValidationException(
message: message,
key: key,
code: code,
Expand All @@ -141,12 +141,12 @@ abstract class LucidValidationBuilder<TProp, Entity> {

/// Adds a validation rule to the LucidValidationBuilder.
///
/// The [rule] parameter is a function that takes an [Entity] object as input and returns a [ValidationError] object.
/// The [rule] parameter is a function that takes an [Entity] object as input and returns a [ValidationException] object.
/// This method adds the [rule] to the list of validation rules in the LucidValidationBuilder.
///
/// Returns the current instance of the LucidValidationBuilder.
LucidValidationBuilder<TProp, Entity> use(
ValidationError? Function(TProp value, Entity entity) rule,
ValidationException? Function(TProp value, Entity entity) rule,
) {
_rules.add((entity) => rule(_selector(entity), entity));
return this;
Expand Down Expand Up @@ -228,24 +228,24 @@ abstract class LucidValidationBuilder<TProp, Entity> {
return this;
}

/// Executes all validation rules associated with this property and returns a list of [ValidationError]s.
List<ValidationError> executeRules(Entity entity) {
/// Executes all validation rules associated with this property and returns a list of [ValidationException]s.
List<ValidationException> executeRules(Entity entity) {
final byPass = _condition?.call(entity) ?? true;
if (!byPass) {
return [];
}

final errors = <ValidationError>[];
final exceptions = <ValidationException>[];

if (_nestedValidator != null) {
final nestedErrors = _nestedValidator!.validate(_selector(entity)).errors;
errors.addAll(nestedErrors);
final nestedExceptions = _nestedValidator!.validate(_selector(entity)).exceptions;
exceptions.addAll(nestedExceptions);
} else {
for (var rule in _rules) {
final error = rule(entity);
final exception = rule(entity);

if (error != null) {
errors.add(error);
if (exception != null) {
exceptions.add(exception);

if (_mode == CascadeMode.stopOnFirstFailure) {
break;
Expand All @@ -254,6 +254,6 @@ abstract class LucidValidationBuilder<TProp, Entity> {
}
}

return errors;
return exceptions;
}
}
8 changes: 4 additions & 4 deletions lib/src/lucid_validator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ abstract class LucidValidator<E> {
.firstOrNull;
}

/// Validates the entire entity [E] and returns a list of [ValidationError]s if any rules fail.
/// Validates the entire entity [E] and returns a list of [ValidationException]s if any rules fail.
///
/// This method iterates through all registered rules and checks if the entity meets all of them.
///
Expand All @@ -86,13 +86,13 @@ abstract class LucidValidator<E> {
/// }
/// ```
ValidationResult validate(E entity) {
final errors = _builders.fold(<ValidationError>[], (previousErrors, builder) {
final exceptions = _builders.fold(<ValidationException>[], (previousErrors, builder) {
return previousErrors..addAll(builder.executeRules(entity));
});

return ValidationResult(
isValid: errors.isEmpty,
errors: errors,
isValid: exceptions.isEmpty,
exceptions: exceptions,
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/types/types.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export 'validation_error.dart';
export 'validation_exception.dart';
export 'validation_result.dart';
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/// Represents an error that occurs during validation.
///
/// [ValidationError] provides details about the validation error, including
/// [ValidationException] provides details about the validation error, including
/// an optional key that identifies which field or property the error is associated with.
class ValidationError {
class ValidationException {
/// The error message describing what went wrong during validation.
final String message;

Expand All @@ -12,11 +12,11 @@ class ValidationError {
/// An optional code that identifies the specific validation error.
final String code;

/// Constructs a [ValidationError].
/// Constructs a [ValidationException].
///
/// [message] provides a description of the error.
/// [key] optionally identifies the field or property related to the error.
const ValidationError({
const ValidationException({
required this.message,
required this.code,
this.key = '',
Expand Down
10 changes: 5 additions & 5 deletions lib/src/types/validation_result.dart
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import 'validation_error.dart';
import 'validation_exception.dart';

/// Represents the result of a validation rule.
///
/// [ValidationResult] encapsulates whether the validation was successful
/// and, if not, provides the associated [ValidationError].
/// and, if not, provides the associated [ValidationException].
class ValidationResult {
/// Indicates whether the validation was successful.
final bool isValid;

/// Provides details about the validation error if the validation failed.
final List<ValidationError> errors;
final List<ValidationException> exceptions;

/// Constructs a [ValidationResult].
///
/// [isValid] specifies whether the validation passed or failed.
/// [errors] provides the errors details in case of a validation failure.
/// [exceptions] provides the exceptions details in case of a validation failure.
const ValidationResult({
required this.isValid,
required this.errors,
required this.exceptions,
});
}
2 changes: 1 addition & 1 deletion lib/src/validations/equal_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ extension EqualValidation<T, E> on LucidValidationBuilder<T, E> {
defaultMessage: message,
);

return ValidationError(message: currentMessage, code: currentCode);
return ValidationException(message: currentMessage, code: currentCode);
},
);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/src/validations/greater_than_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ extension GreaterThanValidation on SimpleValidationBuilder<num> {
defaultMessage: message,
);

return ValidationError(message: currentMessage, code: currentCode);
return ValidationException(message: currentMessage, code: currentCode);
});
}
}
3 changes: 2 additions & 1 deletion lib/src/validations/is_empty_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ extension IsEmptyValidation on SimpleValidationBuilder<String> {
/// ruleFor((user) => user.name, key: 'name')
/// .isEmpty();
/// ```
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
///
Expand All @@ -34,7 +35,7 @@ extension IsEmptyValidation on SimpleValidationBuilder<String> {
defaultMessage: message,
);

return ValidationError(message: currentMessage, code: currentCode);
return ValidationException(message: currentMessage, code: currentCode);
});
}
}
3 changes: 2 additions & 1 deletion lib/src/validations/is_not_null_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ extension IsNotNullValidation<T> on SimpleValidationBuilder<T?> {
/// ruleFor((user) => user.name, key: 'name') // required field
/// .isNotNull();
/// ```
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
///
Expand All @@ -35,7 +36,7 @@ extension IsNotNullValidation<T> on SimpleValidationBuilder<T?> {
defaultMessage: message,
);

return ValidationError(message: currentMessage, code: currentCode);
return ValidationException(message: currentMessage, code: currentCode);
},
);
}
Expand Down
3 changes: 2 additions & 1 deletion lib/src/validations/is_null_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ extension IsNullValidation<T> on SimpleValidationBuilder<T?> {
/// ruleFor((user) => user.name, key: 'name') // optional field
/// .isNull();
/// ```
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
///
Expand All @@ -35,7 +36,7 @@ extension IsNullValidation<T> on SimpleValidationBuilder<T?> {
defaultMessage: message,
);

return ValidationError(message: currentMessage, code: currentCode);
return ValidationException(message: currentMessage, code: currentCode);
},
);
}
Expand Down
27 changes: 22 additions & 5 deletions lib/src/validations/less_then_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,28 @@ extension LessThanValidation on SimpleValidationBuilder<num> {
/// ruleFor((user) => user.discount, key: 'discount')
/// .lessThan(100);
/// ```
SimpleValidationBuilder<num> lessThan(num maxValue, {String message = r'Must be less than $maxValue', String code = 'less_than'}) {
return must(
(value) => value < maxValue,
message.replaceAll('$maxValue', maxValue.toString()),
code,
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
/// - **{ComparisonValue}**: The value to compare against.
///
SimpleValidationBuilder<num> lessThan(num maxValue, {String? message, String? code}) {
return use(
(value, entity) {
if (value < maxValue) return null;

final currentCode = code ?? Language.code.lessThan;
final currentMessage = LucidValidation.global.languageManager.translate(
currentCode,
parameters: {
'PropertyName': key,
'ComparisonValue': '$maxValue',
},
defaultMessage: message,
);

return ValidationException(message: currentMessage, code: currentCode);
},
);
}
}
27 changes: 22 additions & 5 deletions lib/src/validations/matches_pattern_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,28 @@ extension MatchesPatternValidation on SimpleValidationBuilder<String> {
/// ruleFor((user) => user.phoneNumber, key: 'phoneNumber')
/// .matchesPattern(r'^\d{3}-\d{3}-\d{4}$');
/// ```
SimpleValidationBuilder<String> matchesPattern(String pattern, {String message = 'Invalid format', String code = 'invalid_format'}) {
return must(
(value) => RegExp(pattern).hasMatch(value),
message,
code,
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
///
SimpleValidationBuilder<String> matchesPattern(String pattern, {String? message, String? code}) {
return use(
(value, entity) {
final isValid = RegExp(pattern).hasMatch(value);

if (isValid) return null;

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

return ValidationException(message: currentMessage, code: currentCode);
},
);
}
}
29 changes: 24 additions & 5 deletions lib/src/validations/max_length_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,30 @@ extension MaxLengthValidation on SimpleValidationBuilder<String> {
/// ruleFor((user) => user.username, key: 'username')
/// .maxLength(10);
/// ```
SimpleValidationBuilder<String> maxLength(int num, {String message = r'Must be at most $num characters long', String code = 'max_length'}) {
return must(
(value) => value.length <= num,
message.replaceAll(r'$num', num.toString()),
code,
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
/// - **{MaxLength}**: The value to compare against.
/// - **{TotalLength}**: total characters entered.
///
SimpleValidationBuilder<String> maxLength(int num, {String? message, String? code}) {
return use(
(value, entity) {
if (value.length <= num) return null;

final currentCode = code ?? Language.code.maxLength;
final currentMessage = LucidValidation.global.languageManager.translate(
currentCode,
parameters: {
'PropertyName': key,
'MaxLength': '$num',
'TotalLength': '${value.length}',
},
defaultMessage: message,
);

return ValidationException(message: currentMessage, code: currentCode);
},
);
}
}
29 changes: 24 additions & 5 deletions lib/src/validations/max_validation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,30 @@ extension MaxValidation on SimpleValidationBuilder<num> {
/// ruleFor((user) => user.age, key: 'age')
/// .maxLength(18);
/// ```
SimpleValidationBuilder<num> max(num num, {String message = r'Must be less than or equal to $num', String code = 'max_value'}) {
return must(
(value) => value <= num,
message.replaceAll(r'$num', num.toString()),
code,
///
/// String format args:
/// - **{PropertyName}**: The name of the property.
/// - **{MaxValue}**: The maximum value.
/// - **{PropertyValue}**: value entered.
///
SimpleValidationBuilder<num> max(num num, {String? message, String? code}) {
return use(
(value, entity) {
if (value <= num) return null;

final currentCode = code ?? Language.code.max;
final currentMessage = LucidValidation.global.languageManager.translate(
currentCode,
parameters: {
'PropertyName': key,
'MaxValue': '$num',
'PropertyValue': '$value',
},
defaultMessage: message,
);

return ValidationException(message: currentMessage, code: currentCode);
},
);
}
}
Loading

0 comments on commit 3131bc6

Please sign in to comment.