Git Product home page Git Product logo

form-validator's Introduction

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

final builder = ValidationBuilder().email();

TextFormField(
  validator: builder.maxLength(50).build(),
),
TextFormField(
  validator: builder.maxLength(20).build(),
),

Correct

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.

form-validator's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

form-validator's Issues

Passing `ValidationBuilder()` to validator has this error

Passing ValidationBuilder() to validator has this error:
image

This is my code:

  TextField(
                  controller: passwordController,
                  labelText: 'Password',
                  hintText: 'Password',
                  obscureText: true,
                  validator: ValidationBuilder().required().minLength(8).build(),
                ),

And I'm my custom TextField() is

class TextField extends StatelessWidget {
  final String labelText;
  final String hintText;
  final bool? obscureText;
  final TextEditingController controller;
  final FormFieldValidator? validator;

  const TextField({
    Key? key,
    required this.labelText,
    required this.hintText,
    this.obscureText,
    required this.controller,
    this.validator,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
      textInputAction: TextInputAction.next,
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        hintText: hintText,
        labelText: labelText,
      ),
      obscureText: obscureText ?? false,
      validator: validator,
    );
  }
}

Required not working

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Flutter doctor

Open terminal, run "flutter doctor" and copy output here.

Additional context
Add any other context about the problem here.

PatternValidator's pattern param should be type of `String` rather than `Pattern`, which is ambiguous

Describe the bug

PatternValidator(RegExp(r".*")) is a legal based on the method signature, but it doesn't work as expected.
PatternValidator(RegExp(r".*")).isMatch("text") returns false.

To Reproduce
PatternValidator(RegExp(r".*")) is expected to match any text, but it isn't

Expected behavior
PatternValidator(RegExp(r".*")).isMatch("text") should return true, but it returns false.

Flutter doctor

[✓] Flutter (Channel beta, 2.1.0-12.2.pre, on Mac OS X 10.15.5 19F101 darwin-x64, locale en-AU)
    • Flutter version 2.1.0-12.2.pre at /Users/tim.wen/Workspace/flutter
    • Framework revision 5bedb7b1d5 (3 weeks ago), 2021-03-17 17:06:30 -0700
    • Engine revision 711ab3fda0
    • Dart version 2.13.0 (build 2.13.0-116.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /usr/local/lib/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /usr/local/lib/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.4, Build version 12D4e
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio
    • Android Studio at /Applications/Android Studio 4.2 Preview.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.55.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.21.0

[✓] Connected device (3 available)
    • iPhone 12 Pro (mobile) • 8E043A16-17CB-44E0-ADEF-9AD872895BAA • ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
    • macOS (desktop)        • macos                                • darwin-x64     • Mac OS X 10.15.5 19F101 darwin-x64
    • Chrome (web)           • chrome                               • web-javascript • Google Chrome 89.0.4389.114

• No issues found!

Additional context
The fundamental issue isValid method, which convert the pattern to String by calling toString.

@override
bool isValid(String? value) =>
    hasMatch(pattern.toString(), value!, caseSensitive: caseSensitive);

Pattern has 2 implementations: String.toString returns itself. but RegExp.toString doesn't return its pattern.

RegExp(r".*").toString() returns RegExp/.*/.

Splitting required into notBlank and notNull

Is your feature request related to a problem? Please describe.
When using the required validator on a FormField, that can have non String-type values, like many custom FormFields do (like a DatePicker), the current required validator throws an exception, since it tests on value.length > 0. Some FormFields may even return null.

One can imagine FormFields that allow an empty array as valid value, but not null. In this case the current required validator will not work as expected.

Describe the solution you'd like
Replacing required validator with adding notNull and notBlank. Or keeping required but stating it does only work on type String.

Describe alternatives you've considered
none

Additional context
See my pull request

form_validator v2.0.0

I'm planning to release a major update for form_validator to "fix" or "improve" some issues on existing releases.

Here's some of goals I'm planning to improve on next version:

  1. Improving localization extensibility, preferably migrating with flutter localization kit, and supporting localization for custom validators also preferred - related issues: #7
  2. Providing more descriptive api for required and optional validation rules - related issues: #27 #29 #30
  3. Improving email validator. Currently afaik it does accepts emails like user@domain while that's accepted by specs, in real world use cases it's preferred to validate emails to have 2nd level domains. Preferably we can also make email validator customizable so users can use custom regexs for their use case - related issues: #26

If you're currently using form_validator and have any suggestions please let me know below, I'm currently no using this package myself so I'm not sure how else this could be improved further.

Also thanks for being involved in extending localization support and providing various feedbacks 😇

Passing the data in the text editing controller to the validation builder custom extension

Is your feature request related to a problem? Please describe.
I dont know if is possible but i tried to Passing the data in the text editing controller to the validation builder (my custom validation builder extension) but it doesnt work.

Describe the solution you'd like
I want to send the string data I got from the password controller to custom Validator Builder. When I tested it I noticed that, string data in the text editing controller does not reach the validation builder. But then when I try to access it with the regular button, the text editing controller works fine.

Additional context

Text Form Field codes:

child: TextFormField(
                    controller: _repeatPassController,
                    validator: ValidationBuilder(
                            requiredMessage: "Bu alan gereklidir!")
                        .repeatPassword(_passController.text)
                        .build(),
                    obscureText: true,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Tekrar Şifre',
                        hintText: 'Güvenli bir şifre giriniz'),
                  ),

This part of my codes is kept in another file called consts.dart.

extension CustomValidationBuilderRepeatPassword on ValidationBuilder {
  ///check if password repeated
  ///if password is not repeated return error message
  repeatPassword(String password) => add((value) {
        print("password: $password");
        if (value == null || value.isEmpty) {
          return "Bu alan gereklidir";
        }

        if (value != password) {
          print(value + " value");
          print(password + " password");
          return 'Şifreler eşleşmiyor!';
        }
        return null;
      });
}

V1 Roadmap

This issue contains tasks required to be accomplished before v1.0 release.

General

  • Listing
  • Write tests for each validation
    • Length
    • Email
    • Phone
    • IP
    • URL
    • Text comparison
    • Password validation
  • Consider about class naming
  • Simple locale management

Validators

  • Length (min, max)
  • Email
  • Phone
  • IP (v4, v6)
  • URL
  • Text comparison (eg.: password and password repeat should be same)
  • Password validation
    • Min. length
    • Symbols
    • Lowercase letter
    • Uppercase letter
    • Number
  • ???

Languages

  • English
  • Azerbaijani
  • Turkish
  • Russian
  • Chinese
  • ???

Always required

It seems the field is always required

final ValidationBuilder validationBuilder = ValidationBuilder().email('Wrong Email Format');
String? _errorText = validationBuilder.build()(null);

Result "The field is required"

final ValidationBuilder validationBuilder = ValidationBuilder().email('Wrong Email Format');
String? _errorText = validationBuilder.build()('');

Result "Wrong Email Format"

using `required()` on an `optional` field does nothing

Describe the bug
I am using global validator builder, because i want to have the same locale everywhere. bue i have noticed that whenever i am using the optional: true parameter, it overrides future required() method. i feel like it should not be an intended behaviour since the constructor of ValidationBuilder is using required()

    if (!optional) required(requiredMessage);

it should base only on that or change flag optional when we are using required()

Add isEmpty on required string

ValidationBuilder().required("").build()
only works on strings that are null. However when a string is empty "" the validator says that it's valid. I expected an invalid error.

image

How to add a prefix?

Is your feature request related to a problem? Please describe.
How to add a prefix to the message? eg. Field-A is required, Field-B is required, etc.

Describe the solution you'd like
Perhaps, all of the rule can have field as first parameter. So that field can be add to the message.

  ValidationBuilder required() => add((String? field, value) {
        return (value ?? "").isEmpty ? '${(field ?? "Field")} is required' : null;
      });

   ValidationBuilder(prefix: "Field-A").required()
   ValidationBuilder(prefix: "Field-B").required()

Adding new rules with custom i18n error message

As far as i'm aware, there is no way to add both a new custom validation rule and localized error message associated.

It would be great if we could extend both ValidationBuilder and FormValidatorLocale derived classes (eg: LocaleEn) or rethink a bit the way to handle it to enable this feature.

For now the solution is to copy all the localized files and handle the loading according to user's language, which is not very practical.

Add DropdownButtonFormField Support

Is your feature request related to a problem? Please describe.
Make available to use ValidationBuilder not only for TextFormField, but for other elements like DropdownButtonFormField

Describe the solution you'd like

DropdownButtonFormField(
  validator: ValidationBuilder().required().build(),
),

Right now it's returning error

"The argument type 'String? Function(String?)' can't be assigned to the parameter type 'String? Function(dynamic)?'. (Documentation)"

Leverage validators package instead of writing our own regexp

Validation of common idioms via regexp is a tricky business and not something you really want to do yourself. For example, the regexp currently being used to validate emails is actually quite simple:

image

If we were to compare it to the one being define in the validators package:

image

Obviously the latter take into account Unicode characters and probably some other quirks.
I believe it would be better to simply leverage the validators package instead of trying to come up with regexps on our own that we have to maintain and test.

Number input validator

I noticed that the package missed a number input validator which make it possible to check if the input contains only digits.
Can we add this feature

Add a method to add locale to the supported list (instead of using the globalLocale

Is your feature request related to a problem? Please describe.
If I want to add a custom locale and switch to another local on runtime,
When the user change locale, for custom local I need to use the globalLocale, while for supported locale I need to use setLoacel()

Describe the solution you'd like
I want a method like:
ValidationBuilder.addLocale(FormValidatorLocale customLocale);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.