material-input with validation and error message in AngularDart

Issue

I would like to use validation and error message with material-input in AngularDart.

We have a default message error (Enter a number) in this component, as we can see in the figure below:

enter image description here

I need to validate if a percentual field input is between 0 and 100%, for example. If not, a message error should be displayed.

What is the way to work with input validation and error messages in AngularDart with Material Components?

Solution

The components have a couple of validators already written which can help you here.

<material-input type=[percent] [lower]="0" [upper]="100"></material-input>

These validators are coming from here. The error messages are set to percent friendly here. If you wanted to override your own messages you can do that too here is the code. Sorry in advance for any errors whiteboard coding:

import 'package:angular_components/forms/error_renderer.dart';

@Component(
  selector: 'my-form'
  template: '<material-input type="percent" percentErrorRenderer="myErrors">')
class MyForm {
  ErrorFn myErrors = replaceErrors(
    {'lower-bound-number': 'Bigger number please',
     'upper-bound-number': 'Smaller number please'});
}

The error renderer pattern allows you to use the common validators but change the messages to whatever you want. You can also use errorRenderer for regular inputs, but percent needs it’s own attribute since it is directly using input.

If your validation needs to be more complicated than the defaults that are included I suggest you use the validators linked above as an example of creating one.

Answered By – Ted Sander

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.