master_validator

Version GitHub Netlify Status

Live Demo

Simple and quick form validation library for Flutter.

  • Easy to get started with
  • Lightweight
  • Customizable Error Messages
  • Validator Chaining

Getting Started

Installation

Add master_validator as dependency to your flutter project by running the following command in project-root.

flutter pub add master_validator

Then run flutter pub get to install required dependencies.

Check installation tab for more information

Code

Import master_validator package to your dart widgets by writing:

import 'package:master_validator/master_validator.dart';

This makes the Validators class available in your codespace

Basic Required Field Validation

Use Validators.Required() to make a field required.

TextFormField(
    validator: Validators.Required(
        errorMessage : "This field cannot be left empty",
    )
),

Email Validation

TextFormField(
    validator: Validators.Required(
        next : Validators.Email(),
    ),
),

Inbuild Validation methods :

  • Validators.Required()
  • Validators.Email()
  • Validators.Number()
    • with optional integerOnly allowNegative allowDecimal parameters
  • Validators.LengthBetween()
  • Validators.Minlength()
  • Validators.Maxlength()
  • Validators.Url()
  • Validators.Regex()
  • Validators.Equals()
  • Validators.FileName()
  • Validators.DirectoryName()

Every validator has an errorMessage parameter to customize the error message and a next parameter to chain another validator

Using Multiple Validators (Chaining Validators)

All validators take a next argument in which you can specify another validator (a custom function, or another predefined validator) like :

TextFormField(
    validator: Validators.Required(
        next : Validators.Email(
            next : Validators.Maxlength(50)
        ),
    ),
),

Note: While Chaining, Order MATTERS!

NOTE: By default All Validators except Validators.Required() will not throw an error if the data is empty/null, this means if you defined a validator like :

TextFormField(
    validator: Validators.Email(),
),

It means the field acts as an optional field but if something is entered it must qualify as an email, to change this behaviour, and to make the field required, use Validators.Required() before any other validator, for example -

TextFormField(
    validator: Validators.Required(
        next : Validators.Url(),
    ),
),

Master Validator by default also adds up the following extensions to String class :

  • isEmail
  • isInteger
  • isDouble
  • isValidDirectoryName
  • isValidURL
  • hasLengthBetween(min,max)

All of these returns a boolen value which can be used as :

String email = "someone@org.com";

if(email.isEmail){
    print("Valid Email");
}

For detailed usage, check example/lib