form_validator 0.1.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 63

form_validator #

pub package GitHub GitHub Workflow Status codecov

Simplest form validation for flutter form widgets.

  • Zero dependency
  • Localization supported
  • Extensible
  • Well tested
  • Open source

Example #

TextFormField(
  validator: ValidationBuilder().email().maxLength(50).build(),
  decoration: InputDecoration(labelText: 'Email'),
),

live demo

Getting Started #

Installation #

Add form_validator as dependency to your flutter project by adding this lines to pubspec.yaml.

dependencies:
  form_validator: ">=0.1.1 <2.0.0"

Then run flutter pub get to install required dependencies.

Check installation tab for more information

Code #

Import form_validator package to your dart widgets by writing:

import 'package:form_validator/form_validator.dart';

Now you can use ValidationBuilder class to create validation logic. Here's simple validator that validates if input length is between 10 and 50 characters long.

final validate = ValidationBuilder().minLength(10).maxLength(50).build();

print(validate('test'));        // Minimum length must be at least 10 characters
print(validate('Hello World')); // null, means value is correct

Localization #

You can set global locale using ValidationBuilder.setLocale(String localeName) or you can also define locale on ValidationBuilder({ String localeName }) constructor.

ValidationBuilder.setLocale('en');

// will use *en* localization
ValidationBuilder()
  .minLength(5)
  .build();

// will use *az* localization
ValidationBuilder(localeName: 'az')
  .minLength(5)
  .build();

// will display custom message
ValidationBuilder()
  .minLength(5, 'Length < 5 😟')
  .build();

Methods #

.minLength(int minLength, [String message]) #

Validates if value length is not less than minLength.

.maxLength(int maxLength, [String message]) #

Validates if value length is not more than maxLength.

.email([String message]) #

Checks if value is an email address.

.phone([String message]) #

Checks if value is an phone number.

Note: This method might be changed in future.

.ip([String message]) #

Checks if value is correct IPv4 address.

.ipv6([String message]) #

Checks if value is correct IPv6 address.

.url([String message]) #

Checks if value is correct url address.

.regExp(RegExp regExp, String message) #

Validates if value does matches regExp or not.

message argument is required in this method.

.or(Action<ValidationBuilder> left, Action<ValidationBuilder> right, {bool reverse = false}) #

Validates if value passes any of left and right validations. If value doesn't passes any error message from right validation will be displayed (If reverse set to true message from left validation will be displayed).

Example:

print(
  ValidationBuilder().or(
    (builder) => builder.email('not email'),
    (builder) => builder.phone('not phone'),
  )
  .test('invalid')
); // not phone

print(
  ValidationBuilder().or(
    (builder) => builder.email('not email'),
    (builder) => builder.phone('not phone'),
    reverse: true,
  )
  .test('invalid')
); // not email

Notes #

ValidationBuilder is mutable. #

You need to construct different instances for each validation.

Wrong Correct
final builder = ValidationBuilder().email();

TextFormField(
  validator: builder.maxLength(50).build(),
),
TextFormField(
  validator: builder.maxLength(20).build(),
),
final validator1 = ValidationBuilder().email().maxLength(50).build();
final validator2 = ValidationBuilder().email().maxLength(20).build();

TextFormField(
  validator: validator1,
),
TextFormField(
  validator: validator2,
),

Add custom localization #

Firstly you need to extend abstract FormValidatorLocale class.

import 'package:form_validator/form_validator.dart';

class MyValidationLocale extends FormValidatorLocale {
  @override
  String name() => "custom";

  @override
  String required() => "Field is required";

  ...
}

PROTIP: You can copy a language file from /lib/src/i18n folder and modify messages as you want.

Then you can use your custom locale class as global or local validation locale.

// global locale
void main() {
  ValidationBuilder.globalLocale = MyValidationLocale();
  ...
}

// local locale
final locale = MyValidationLocale();

build(BuildContext context) {
  final emailValidator = ValidationBuilder(locale: locale)
    .email()
    .build();
  ...
}

PROTIP: Feel free to add your locale to library by opening pull request TheMisir/form-validator to support library.

Extending ValidationBuilder #

You can use dart extension methods to extend ValidationBuilder.

extension CustomValidationBuilder on ValidationBuilder {
  password() => add((value) {
    if (value == 'password') {
      return 'Password should not "password"';
    }
    return null;
  });
}

final validator = ValidationBuilder().password().build();

Support #

If you would like to support this library you could translate messages to your own language.

[0.1.3] - 6/13/2020 #

  • Added turkish language

[0.1.2] - 6/12/2020 #

  • Added messages for english

[0.1.1+2] - 6/7/2020 #

  • Added documentation

[0.1.1] - 6/7/2020 #

  • Added example

[0.1.0] - 6/7/2020 #

  • Initial release

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:form_validator/form_validator.dart';

void main() {
  runApp(MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
      primarySwatch: Colors.blue,
      visualDensity: VisualDensity.adaptivePlatformDensity,
    ),
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  GlobalKey<FormState> _form = GlobalKey<FormState>();

  void _validate() {
    _form.currentState.validate();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Example'),
      ),
      body: Form(
        key: _form,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(15),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextFormField(
                validator: ValidationBuilder().email().maxLength(50).build(),
                decoration: InputDecoration(labelText: 'Email'),
              ),
              SizedBox(height: 30),
              TextFormField(
                validator:
                    ValidationBuilder().minLength(5).maxLength(50).build(),
                decoration: InputDecoration(
                  labelText: 'Name',
                  helperText: 'Min length: 5, max length: 50',
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _validate,
        tooltip: 'Next',
        child: Icon(Icons.arrow_forward),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  form_validator: ^0.1.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:form_validator/form_validator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
26
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
63
Learn more about scoring.

We analyzed this package on Jul 9, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14

Health suggestions

Format lib/src/i18n/tr.dart.

Run dartfmt to format lib/src/i18n/tr.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
Dev dependencies
test ^1.0.0