reactive_forms icon indicating copy to clipboard operation
reactive_forms copied to clipboard

Validator Question

Open BC89 opened this issue 3 years ago • 1 comments

Greetings.

Thanks for this great package. If you can spare a minute, I would like a bit of advice on the implementation strategy for adding inputs and validations on the fly based on a database table query. My table looks like so: image

Each project has it's own configuration that determines whether the input IsRequired or has Min/Max chars etc.

I've been successful with building the FormControl per record and associating to the ReactiveForm and formGroup. The layout is working and seems nearly to meet my needs. Where I'm stumped is how to add validations to the _formControl.

The ideal scenario would be something akin to the following:

FormControl _buildControl(Db_Client_Field_Mapping _clientField) {
  var _formControl = FormControl();

  if (_clientField.FieldType == 'TimeField') {
    _formControl = FormControl<TimeOfDay>();
  } else if (_clientField.FieldType == 'DateField') {
    _formControl = FormControl<DateTime>();
  } else if (_clientField.FieldType == 'NumberField') {
    _formControl = FormControl<double>();
  } else {
    _formControl = FormControl<String>();
  }
....

if (_clientField.IsRequired! > 0) {
    _formControl.validators.add(Validators.required);
  }

  if (_clientField.MinChars! > 0) {
    _formControl.validators.add(Validators.min(_clientField.MinChars));
  }

  if (_clientField.MaxChars! > 0) {
    _formControl.validators.add(Validators.max(_clientField.MaxChars));
  }

return _formControl;

But the only way I see to do it is as follows which clears previous validators: _formControl.setValidators([Validators.required]);

Which means I would need to find a way to do the following: _formControl.setValidators([Validators.required, Validators.max(_clientField.MaxChars), Validators.min(_clientField.MinChars)]);

Thank you!

BC89 avatar Oct 19 '22 16:10 BC89

Why are you adding them one by one?) Just dump validators into list and set at the very end of your _buildControl


final list = [];

list.add(validator);
list.add(validator1);
list.add(validator2);
list.add(validator3);

_formControl.setValidators(list);

vasilich6107 avatar Oct 28 '22 09:10 vasilich6107