Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions lib/src/validators/number_validator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import 'package:reactive_forms/src/validators/number_validator_error.dart';
/// ```
class NumberValidator extends Validator<dynamic> {
/// The regex expression of a numeric string value.
static final RegExp notNumbersRegex = RegExp(r'[^0-9.]');
static final RegExp notNumbersRegex = RegExp(r'[^0-9.,]');

/// The allowed number of decimal places in the validated string.
///
Expand Down Expand Up @@ -74,11 +74,11 @@ class NumberValidator extends Validator<dynamic> {
@override
Map<String, dynamic>? validate(AbstractControl<dynamic> control) {
// Skip validation if null value is allowed
if (allowNull && control.value == null) {
if (allowNull && _isControlNullOrEmptyString(control)) {
return null;
}

if (control.value == null) {
if (_isControlNullOrEmptyString(control)) {
return <String, dynamic>{
ValidationMessage.number: NumberValidatorError.nullValue,
};
Expand Down Expand Up @@ -125,10 +125,11 @@ class NumberValidator extends Validator<dynamic> {
}

bool _validateNumberDecimals(int allowedDecimals, String numberString) {
final deLocalizedNumberString = numberString.replaceAll(',', '.');
// Split the number string at the decimal point
final parts = numberString.split('.');
final parts = deLocalizedNumberString.split('.');

if (parts.length > 2 || numberString == '.' || numberString.endsWith('.')) {
if (parts.length > 2 || deLocalizedNumberString == '.' || deLocalizedNumberString.endsWith('.')) {
// More than one decimal point, invalid format
return false;
}
Expand All @@ -141,4 +142,8 @@ class NumberValidator extends Validator<dynamic> {
// Check if the decimal part length is within the allowed limit
return parts[1].length <= allowedDecimals;
}

static bool _isControlNullOrEmptyString(AbstractControl<dynamic> control) =>
control.value == null ||
(control.value is String && (control.value as String).isEmpty);
}
10 changes: 5 additions & 5 deletions lib/src/validators/number_validator_error.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class NumberValidatorError {
static const String nullValue = 'nullValue';
static const String invalidDecimals = 'invalidDecimals';
static const String unsignedNumber = 'unsignedNumber';
static const String invalidNumber = 'invalidNumber';
enum NumberValidatorError {
nullValue,
invalidDecimals,
unsignedNumber,
invalidNumber,
}