validation_extensions 1.0.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 86

validation_extensions #

Flutter form field validations using dart extension methods.

Available validation extension methods #

String extension methods #

Check tests file for examples on how to use them or the example app.

MethodParametersDescription
isRequiredNoneValidates if the string in not empty
isEmailNoneValidates if the string is a valid email address
minLengthint minValidates if the string length is longer than min
maxLengthint maxValidates if the string length is shorter than max
lengthRangeint min, int maxValidates if the string length is longer than min and shorter than max
matchString stringToMatchValidates if the string is an exact match of the String stringToMatch parameter that you provide
matchPatternString regExpValidates if the string matches the regular expression regExp parameter that you provide
isIntNoneValidates if the string is a valid integer
isDoubleNoneValidates if the string is a valid double
minint minValidates if the string is a valid double bigger than min
maxint maxValidates if the string is a valid double smaller than max
rangeint min, int maxValidates if the string is a valid double between min and max

Note

You have to use isRequired to make a field mandatory, all other extension methods won't validate empty string, and will validate only if string is not empty which will make the field optional.

List<Function> extension methods #

MethodDescription
validateexecute validation functions one by one, will stop execution when it encounter a validation error and return the errorText

Usage #

All extension methods return type is Function, you have to use double parentheses to execute the returned function for single validations.

Form(
      key: _formKey,
      child: TextFormField(
          validator: (v) => v.isRequired()(),
        ),
      ),

Multi validations #

For multi rules validation put your validation in a list and call validate() extension method on the list, it will execute validation one by one, it will stop execution when it encounter the first validation error and return the errorText to increase performance.

Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            onChanged: (v) => password = v,
            validator: (v) => [
              v.isRequired(),
              v.minLength(8),
            ].validate(),
          ),
          TextFormField(
            validator: (v) => [
              v.isRequired(),
              v.match(password),
            ].validate(),
          ),
        ],
      ),
    ),

Custom validations #

If you want to use you own validations in multi rule validation, your validation rules must be: Function that returns a Function that returns a String.

Function customValidation(v) {
	return(){
			return v != "Validation logic" ? "Invalid input" : null;
	};
}

Form(
     key: _formKey,
     child: TextFormField(
        autovalidate: true,
        validator: (v) => [
			v.isRequired(),
	        customValidation(v),
        ].validate(),
      ),
    ),

Custom error message #

Pass the optional named parameter errorText to the extension method to override the default error message

Form(
      key: _formKey,
      child: TextFormField(
        onChanged: (v) => password = v,
        validator: (v) => [
          v.isRequired(
            errorText: "Password is required",
          ),
          v.minLength(
            8,
            errorText: "Password can not be less than 8 characters",
          ),
        ].validate(),
      ),
    ),

[1.0.0] - 2020-04-16 #

  • initial release.

[1.0.1] - 2020-04-16 #

  • Changed some errorMessage.
  • Made validations optional unless input is not empty or isRequired is specified.

example/lib/main.dart

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

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "validation_extensions demo",
      home: DemoForm(),
    );
  }
}

class DemoForm extends StatefulWidget {
  @override
  _DemoFormState createState() => _DemoFormState();
}

class _DemoFormState extends State<DemoForm> {
  final _formKey = GlobalKey<FormState>();

  String password;

  String usernameValidation(String v) => v.isRequired()();

  String emailValidation(String v) => [v.isRequired(), v.isEmail()].validate();

  String ageValidation(String v) =>
      v.min(18, errorText: "You must be older than 18")();

  String passwordValidation(String v) => [
        v.isRequired(),
        v.minLength(8),
      ].validate();

  String confirmPasswordValidation(String v) => [
        v.isRequired(),
        v.minLength(8),
        v.match(password),
      ].validate();

  validate() {
    _formKey.currentState.validate();
  }

  resetForm() {
    _formKey.currentState.reset();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Demo"),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Form(
            key: _formKey,
            child: Column(
              children: <Widget>[
                TextFormField(
                  validator: usernameValidation,
                  decoration: InputDecoration(
                    labelText: "Username*",
                  ),
                ),
                TextFormField(
                  validator: emailValidation,
                  decoration: InputDecoration(
                    labelText: "Email address*",
                  ),
                ),
                TextFormField(
                  validator: ageValidation,
                  decoration: InputDecoration(
                      labelText: "Age", hintText: "Optional age"),
                ),
                TextFormField(
                  validator: passwordValidation,
                  obscureText: true,
                  onChanged: (v) => password = v,
                  decoration: InputDecoration(
                    labelText: "Password*",
                  ),
                ),
                TextFormField(
                  validator: confirmPasswordValidation,
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: "Confirm password*",
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      RaisedButton(
                        color: Colors.lightBlue,
                        onPressed: validate,
                        child: Text("Validate"),
                      ),
                      RaisedButton(
                        color: Colors.redAccent,
                        onPressed: resetForm,
                        child: Text("Reset form"),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  validation_extensions: ^1.0.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support 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:validation_extensions/validation_extensions.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
72
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
86
Learn more about scoring.

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

  • Dart: 2.8.4
  • pana: 0.13.15
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • validation_extensions that is a package requiring null.

Health issues and suggestions

Document public APIs. (-1 points)

17 out of 17 API elements have no dartdoc comment.Providing good documentation for libraries, classes, functions, and other API elements improves code readability and helps developers find and use your API.

Format lib/validation_extensions.dart.

Run flutter format to format lib/validation_extensions.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12 1.14.13
meta 1.1.8 1.2.2
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
Dev dependencies
flutter_test