joanpablo / reactive_forms

This is a model-driven approach to handling form inputs and validations, heavily inspired in Angular's Reactive Forms
MIT License
471 stars 90 forks source link

NumberValidator(allowedDecimals) not working as intended #466

Open cledoux95 opened 1 month ago

cledoux95 commented 1 month ago

Environment

17.0.1

No Flutter Doctor output here, just a runtime bug when attempting to use the NumberValidator

Code sample I'm using reactive_forms_generator, but the principle is the same: Model: ``` @RfGroup class MyClass { double? price; // Signed decimal where I want to enforce a maximum length MyClass({ @RfControl( validators: [NumberValidator(allowedDecimals: 2)]) this.price, }); } ``` UI Code: ``` ReactiveTextField( formControl: formModel.MyClassForm.priceControl, validationMessages: { ValidationMessage.number: (_) => 'Cannot have more than 2 decimals', }, valueAccessor: DoubleValueAccessor(), keyboardType: const TextInputType .numberWithOptions(decimal: true), decoration: InputDecoration( labelText: 'Price', ), ```

Description

Expected behavior: According to the docs within the NumberValidator: reactive_forms-17.0.1/lib/src/validators/number_validator.dart:

...
  /// The allowed number of decimal places in the validated string.
  ///
  /// This value **specifies the maximum number of digits allowed** after the
  /// decimal point in the validated string. Defaults to 0 (no decimals).
  final int allowedDecimals;
...

Current behavior:

In the same file, line 107 only allows for exactly that number of decimals, not up to the maximum, as stated in the comments within the file:

    // Check if the decimal part length is equal to the allowed decimals
    return parts[1].length == allowedDecimals; // <-- Should be '<='

Steps to reproduce

Utilize the NumberValidator with allowedDecimals set to any number greater than 1.

Images

Working text input:

Screen Shot 2024-09-29 at 9 23 57 PM

Working with exactly two decimal places

Screen Shot 2024-09-29 at 9 24 11 PM

Not working with less than two decimal places

Screen Shot 2024-09-29 at 9 24 20 PM