diff --git a/lib/src/validators/number_validator.dart b/lib/src/validators/number_validator.dart index 2dd322d..10803c9 100644 --- a/lib/src/validators/number_validator.dart +++ b/lib/src/validators/number_validator.dart @@ -16,6 +16,9 @@ class NumberValidator extends Validator { /// decimal point in the validated string. Defaults to 0 (no decimals). final int allowedDecimals; + /// Whether the validator allows null values. + final bool allowNull; + /// Whether the validator allows negative numbers. /// /// If set to `true`, the validator will accept strings representing @@ -27,12 +30,18 @@ class NumberValidator extends Validator { /// [allowedDecimals] (optional): The allowed number of decimal places. Defaults to 0. /// [allowNegatives] (optional): Whether to allow negative numbers. Defaults to true. const NumberValidator({ + this.allowNull = false, this.allowedDecimals = 0, this.allowNegatives = true, }) : super(); @override Map? validate(AbstractControl control) { + // Skip validation if null value is allowed + if (allowNull && control.value == null) { + return null; + } + if (control.value == null) { return { ValidationMessage.number: NumberValidatorError.nullValue, diff --git a/lib/src/validators/validators.dart b/lib/src/validators/validators.dart index e587b4b..7ef9926 100644 --- a/lib/src/validators/validators.dart +++ b/lib/src/validators/validators.dart @@ -37,10 +37,12 @@ class Validators { /// [allowedDecimals] (optional): The allowed number of decimal places. Defaults to 0. /// [allowNegatives] (optional): Whether to allow negative numbers. Defaults to true. static Validator number({ + bool allowNull = false, int allowedDecimals = 0, bool allowNegatives = true, }) => NumberValidator( + allowNull: allowNull, allowedDecimals: allowedDecimals, allowNegatives: allowNegatives, ); diff --git a/test/src/validators/number_validator_test.dart b/test/src/validators/number_validator_test.dart index d6354dd..ff2f63f 100644 --- a/test/src/validators/number_validator_test.dart +++ b/test/src/validators/number_validator_test.dart @@ -13,6 +13,25 @@ void main() { expect(control.hasError(ValidationMessage.number), true); }); + test('FormControl invalid if value is null', () { + final control = FormControl(validators: [Validators.number()]); + + expect(control.valid, false); + expect(control.hasError(ValidationMessage.number), true); + expect(control.errors, { + ValidationMessage.number: NumberValidatorError.nullValue, + }); + }); + + test('FormControl valid if value is null and null values is allowed', () { + final control = FormControl( + validators: [Validators.number(allowNull: true)], + ); + + expect(control.valid, true); + expect(control.hasError(ValidationMessage.number), false); + }); + test('FormControl valid if a number', () { final control = FormControl(validators: [Validators.number()]);