form_warden

A very simple package to help you write robust, reusable and extendable validations to go with your Flutter Forms.

Alt text

Installation

To use this package, add form_warden as a dependency in your pubspec.yaml file.

Usage

Import the package

import 'package:form_warden/form_warden.dart';

Required field (inbuilt-validator)

TextFormField(
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: createWarden([Validators.required]),
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: f.label,
    ),
    onSaved: null,
),

Required email field (using inbuilt validator)

TextFormField(
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: createWarden([Validators.required, Validators.email]),
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: f.label,
    ),
    onSaved: null,
),

Custom validator

ValidatorFunction greaterThanTen = (value) {
    if (value is int && value > 10) {
        return null;
    }
    return "Must be greater than 10";
};
TextFormField(
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: createWarden([greaterThanTen]),
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: f.label,
    ),
    onSaved: null,
)

Club multiple validators together to create robust validators

ValidatorFunction greaterThanTen = (value) {
    if (value is int && value > 10) {
        return null;
    }
    return "Must be greater than 10";
};
ValidatorFunction lessThanHundred = (value) {
    if (value is int && value < 100) {
        return null;
    }
    return "Must be less than 100";
};

TextFormField(
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: createWarden([greaterThanTen, lessThanHundred]),
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: f.label,
    ),
    onSaved: null,
)

Using higher order functions create configurable validators

ValidatorFunction between(int lowerLimit, int upperLimit) {
  ValidatorFunction greaterThanLowerLimit = (dynamic? value) {
    if (value.isEmpty) return null;
    var _v = int.parse(value);
    if (_v > lowerLimit && _v < upperLimit) return null;
    return "Value must be between $lowerLimit and $upperLimit";
  };
  return greaterThanLowerLimit;
}
TextFormField(
    autovalidateMode: AutovalidateMode.onUserInteraction,
    validator: createWarden([between(10, 100)]),
    decoration: InputDecoration(
        border: OutlineInputBorder(),
        labelText: f.label,
    ),
    onSaved: null,
)

License

MIT

Libraries

form_warden