Generic validator - A generic validator with business logic separation in mind

Overview

This package provides APIs to facilitate separating validation and business rules from the application presentation.

Features

  • Express your rules in a declarative way.
  • Feedback doesn't have to be of a certain type (totally generic)
  • Group related rules together and eliminate if else statements.
  • Supports asynchronous evalution of rules.

Usage

Check /example for a full detailed usage.

You can declare a ValidationRule with a ruler which encapsulates your validation and of course the negativeFeedback of your choice which can be of any type then call apply on it.

final myName = 'Ahmed';
final arabicName = 'احمد';
final nameRule = ValidationRule(
            ruler: (value) {
              if (RegExp("[A-Za-z]").hasMatch(value)) {
                return true;
              }
              return false;
            },
            negativeFeedback: "Name has to be in English");
final validResult = nameRule.apply(myName); // Returns Valid
final invalidResult = nameRule.apply(arabicName); // Returns Invalid which has a reasons property of the type of the negative feedback passed earlier.

Grouping rules together can be convenient in that case, you can subclass the Validator and override its rules getter declaring your rules.

class NameValidator extends Validator<String, dynamic> {
  @override
  List<ValidationRule<String, dynamic>> get rules => [
      ValidationRule(
            ruler: (value) {
              if (value.isNotEmpty){
                return true;
              }
              return false;
            },
            negativeFeedback: "Name can't be empty"),
        ValidationRule(
            ruler: (value) {
              if (RegExp("[A-Za-z]").hasMatch(value)) {
                return true;
              }
              return false;
            },
            negativeFeedback: "Name has to be in English"),
      ];
}

Call validate on it to get the result:

  
  final aValidName = "Ahmed";
  final invalidName = "";
  final nameValidator = NameValidator();
  final validResult = nameValidator.validate(aValidName); // Returns Valid
  final invalidResult = nameValidator.validate(invalidName); // Returns Invalid with a reasons property

You can also mixin StringRules which has common rules like notEmpty

class NameValidator extends Validator<String, dynamic> with StringRules {
  @override
  List<ValidationRule<String, dynamic>> get rules => [
        notEmpty<String>(negativeFeedback: "This field can't be empty."),
        max(
            maxLength: 10,
            negativeFeedback: "Name can't be more than 10 characters."),
        ValidationRule(
            ruler: (value) {
              if (RegExp("[A-Za-z]").hasMatch(value)) {
                return true;
              }
              return false;
            },
            negativeFeedback: "Name has to be in English"),
      ];
}

You can create both an AsyncValidationRule and an AsyncValidator which can have both ValidationRule and AsyncValidationRules rules.

A validation result have a couple of convient methods like when, maybeWhen, map, and maybeMap. for usages like:

// Map validation result objects to String or null for use with the TextFormfield validator function.
nameValidator.validate(val).maybeMap(
    invalid: (invalid) => invalid.reasons.first,
    orElse: () => null,
);
// Side effects based on a validation result.
phoneValidator.validate(val).maybeWhen(
      invalid: (reasons) {
        // show a dialog
      },
      orElse: () {
        // pop the current screen
      },
);
You might also like...

Connect your flutter app to firebase, use firebase's Authentication. Don't mind my poor UI. 😬

flutter_email_auth A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you start

May 2, 2022

🇮🇪 A generic programming language interpreter, linter, formatter, and all that jazz, written in Dart.

Irishman 🇮🇪 A generic programming language interpreter, linter, formatter, and all that jazz, written in Dart. Installation To install this package

Oct 8, 2022

The Sculptor of your mind.

FreeUp-The Sculptor of your mind. Introduction Its a journal app/AI friend app made using Flutter and AI chatbot. It aims to provide different functio

Nov 14, 2022

Open source Flutter-based template for a business assistant application

Open source Flutter-based template for a business assistant application

TallyAssist TallyAssist is an open source Flutter-based template for a business assistant application. It has been designed to use Google Firebase as

Jan 1, 2023

Venda is a location-based business platform

Venda is a location-based business platform

Venda (vendaround.com) Venda is a location-based business platform that enables people to discover businesses around them. With Venda, you can sell or

Jul 24, 2022

A Flutter project to show a personal business card. 📱ℹ️

Mi Card Mi Card Flutter (Practice Project) 📱 ℹ 💳 What is Mi Card Mi Card is a personal business card. Imagine every time you wanted to give someone

Jan 4, 2022

This mobile application is used to record sales and purchases for a business

This mobile application is used to record sales and purchases for a business, show which sales were paid and which ones are not hence provision of ease track of debtors. The app simplifies the overall business calculations for easy management, monitoring and control.

Aug 22, 2022

Startup-Name-Generator-App-in-Flutter - Business Startup Name Generator App in Flutter

Startup-Name-Generator-App-in-Flutter - Business Startup Name Generator App in Flutter

Business Startup Name Generator App #About APP: A simple mobile app that generat

Jan 30, 2022

Mobile app for small food business have more results spending almost nothing.

ilunch Mobile app for small food business have more results spending almost nothing. Getting Started This project is a starting point for a Flutter ap

Nov 17, 2022
Comments
  • refactor: Suggest new name

    refactor: Suggest new name

    https://github.com/ahmdaeyz/generic_validator/blob/11b5e91bd99064bddbfadfcac5ebc6f0f8d20e8c/lib/src/rule/validation_rule.dart#L16 I think it should be validate not apply as it validate current rule against input passed to method.

    suggestion 
    opened by MahmoudMabrok 2
Owner
Ahmed Aboelyazeed
Blessed is He Who Expects Nothing, for He Shall Never Be Disappointed.
Ahmed Aboelyazeed
Learn how to build a multi-step form flow and how to use bloc to effectively isolate the presentation layer from the business logic layer.

Multi-page Form Flow Learn how to build a multi-step form flow and how to use bloc to effectively isolate the presentation layer from the business log

Sandip Pramanik 15 Dec 19, 2022
A state management library that enables concise, fluid, readable and testable business logic code.

Creator is a state management library that enables concise, fluid, readable, and testable business logic code. Read and update state with compile time

Xianzhe Liang 181 Dec 24, 2022
Business Card - Business Card App Built With Flutter

Business Card app. Basic single page app with functionality. For now you can cha

buraktaha 5 Apr 20, 2022
Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to tidily bound separated logic into complex solution.

Flutter Control is complex library to maintain App and State management. Library merges multiple functionality under one hood. This approach helps to

Roman Hornak 23 Feb 23, 2022
Dart generic app exceptions, mainly aimed at flutter

Micro dart library that expose generic exceptions. The goal of this library is to for the end user to rethrow exceptions of other libraries with the s

cedvdb 2 Dec 31, 2022
Weather app using Bloc architecture pattern & generic HTTP client with interface implementation and much more for more detail read Readme

weather Weather application for current weather, hourly forecast for 48 hours, Daily forecast for 7 days and national weather alerts. How to Run Insta

Jibran Ahmed SiddiQui 9 Oct 29, 2022
A collection of useful algorithms in Dart with keeping performance and flexibility on mind.

algorithmic A collection of useful algorithms in Dart with keeping performance and flexibility on mind. Usage The following import will give you acces

Sudipto Chandra 7 Jan 1, 2023
Simple app for easy shopping list making, developed with simplicity in mind.

Fast Shopping Fast Shopping is a mobile application developed with simplicity in mind. It allows you on having a simple set of shopping lists, that yo

Albert Wolszon 208 Dec 31, 2022
Hack&Heal hybrid hackathon 2022 - Body & Mind topic

Meditation App Hack&Heal hybrid hackathon 2022 - Body & Mind topic The MVP is available for mobile browsers here. The Problem 3.6 million citizens hav

Lorenzo Fiorini 4 Jun 19, 2022