flutter_smart_validator 0.1.1 copy "flutter_smart_validator: ^0.1.1" to clipboard
flutter_smart_validator: ^0.1.1 copied to clipboard

A clean, chainable, and developer-friendly form validation package for Flutter. Build complex validation rules with minimal boilerplate using a fluent API.

Smart Form Validator #

pub package License: MIT Platform

A clean, chainable, and developer-friendly form validation package for Flutter. Build complex validation rules with minimal boilerplate using a fluent API.

// Simple, elegant, powerful
TextFormField(
  validator: SmartValidator()
      .required()
      .email()
      .minLength(8)
      .build(),
)

โœจ Why Smart Form Validator? #

Problem Solution
๐Ÿ˜ซ Verbose validation code โœ… Chainable API - One line, infinite rules
๐Ÿ” Repetitive boilerplate โœ… Built-in rules - 9+ validators ready to use
๐Ÿ“ก Complex async validation โœ… Debounced async - API calls made simple
๐ŸŽจ Inconsistent UI feedback โœ… Optional widgets - Beautiful, consistent UI
๐Ÿ”ง Hard to customize โœ… Custom rules - Add any validation logic
๐Ÿ“š Poor documentation โœ… 5 example demos - Learn by doing

๐Ÿš€ Features #

Core Capabilities #

  • โ›“๏ธ Fluent Chainable API - Readable, maintainable validation rules
  • ๐Ÿ“ฆ 13+ Built-in Rules - Required, email, length, number, case, matching, regex, url, phone, credit card, and more
  • ๐Ÿ”Œ Custom Validation - Extend with your own logic in seconds
  • โšก Async Support - Debounced API validation (username availability, etc.)
  • ๐Ÿ’ก Live Hints - Real-time feedback as users type
  • ๐ŸŽจ UI Widgets - Pre-built components for errors, hints, and password strength
  • ๐Ÿ”— Field Matching - Password confirmation made easy
  • ๐ŸŒ Platform Agnostic - Works everywhere Flutter runs
  • ๐Ÿ“ฑ Zero Dependencies - Only requires Flutter SDK

Developer Experience #

  • ๐ŸŽฏ Type-safe - Null safety and strong typing
  • ๐Ÿ“– Well-documented - Clear examples and API docs
  • ๐Ÿงช Tested - Comprehensive unit tests
  • ๐Ÿ”„ Flexible - Use with forms, controllers, or standalone
  • ๐ŸŽ“ Easy to learn - Start validating in 60 seconds

๐Ÿ“ฆ Installation #

Add to your pubspec.yaml:

dependencies:
  flutter_smart_validator: ^0.1.1

Then install:

flutter pub get

Import in your Dart file:

import 'package:flutter_smart_validator/flutter_smart_validator.dart';

๐ŸŽฏ Quick Start #

Basic Example #

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

class LoginForm extends StatelessWidget {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            validator: SmartValidator()
                .required(message: 'Email is required')
                .email()
                .build(),
          ),
          TextFormField(
            decoration: InputDecoration(labelText: 'Password'),
            obscureText: true,
            validator: SmartValidator()
                .required()
                .minLength(8)
                .uppercase()
                .number()
                .build(),
          ),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                // Form is valid - proceed with login
              }
            },
            child: Text('Login'),
          ),
        ],
      ),
    );
  }
}

That's it! ๐ŸŽ‰ You now have elegant, powerful validation with minimal code.


๐Ÿ“š Built-in Validation Rules #

Rule Description Example
required() Field cannot be empty .required(message: 'Required')
email() Valid email format .email()
minLength(n) Minimum n characters .minLength(8)
maxLength(n) Maximum n characters .maxLength(50)
number() Numeric value with optional range .number(min: 0, max: 100)
uppercase() Contains uppercase letters .uppercase(minCount: 2)
lowercase() Contains lowercase letters .lowercase(minCount: 1)
regex() Matches RegExp pattern .regex(RegExp(r'^[A-Z]+$'))
url() Valid URL format .url()
creditCard() Valid Credit Card (Luhn) .creditCard()
phone() Valid Phone Number .phone()
matchField() Matches another field value .matchField('password', 'Password')
custom() Your custom logic .custom((v) => /* logic */)

Combine any rules together:

SmartValidator()
  .required()
  .email()
  .minLength(10)
  .maxLength(100)
  .build()

Dynamic Custom Messages #

You can use {min} and {max} placeholders in your custom error messages for length and number rules:

SmartValidator()
  .minLength(8, message: 'Must be at least {min} characters')
  .number(min: 10, max: 50, message: 'Value must be between {min} and {max}')

๐ŸŒŸ Advanced Features #

1. Live Validation Hints #

Show progressive feedback as users type:

class PasswordField extends StatefulWidget {
  @override
  State<PasswordField> createState() => _PasswordFieldState();
}

class _PasswordFieldState extends State<PasswordField> {
  final _validator = SmartValidator()
      .required()
      .minLength(8)
      .uppercase()
      .lowercase()
      .number();

  String _password = '';

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextFormField(
          onChanged: (value) => setState(() => _password = value),
          validator: _validator.build(),
        ),
        ValidationHintsList(
          hints: _validator.getLiveHints(_password),
        ),
      ],
    );
  }
}

2. Password Strength Indicator #

PasswordStrengthIndicator(
  password: currentPassword,
  showLabel: true,
  showSuggestions: true,
)

3. Async Validation (API Calls) #

Perfect for checking username/email availability:

final asyncValidator = AsyncValidator(
  (value) async {
    // Call your API
    final response = await checkUsernameAvailability(value);

    if (response.isTaken) {
      return ValidationResult.invalid('Username is taken');
    }
    return ValidationResult.valid();
  },
  debounceMilliseconds: 500,  // Prevents excessive API calls
  syncRules: [
    RequiredRule(),
    MinLengthRule(3),
  ],
);

// Use it
final result = await asyncValidator.validate('john_doe');

4. Custom Validation Rules #

Add any logic you need:

TextFormField(
  validator: SmartValidator()
      .required()
      .custom((value) {
        if (!value!.endsWith('@company.com')) {
          return 'Must be a company email';
        }
        return null;  // Valid
      })
      .build(),
)

5. Field Matching (Password Confirmation) #

final passwordController = TextEditingController();

// Password field
TextFormField(
  controller: passwordController,
  validator: SmartValidator().required().minLength(8).build(),
)

// Confirm password field
TextFormField(
  validator: SmartValidator({
    'password': passwordController.text,  // Context
  })
      .required()
      .matchField('password', 'Password')
      .build(),
)

### 6. New Specialized Rules (v0.1.0)

```dart
// URL validation
SmartValidator().url().build();

// Phone number validation
SmartValidator().phone().build();

// Credit card (Luhn algorithm)
SmartValidator().creditCard().build();

// Custom Regex
SmartValidator().regex(RegExp(r'^[A-Z]+$'), message: 'Uppercase only').build();

7. Get All Errors #

Instead of stopping at the first error:

final validator = SmartValidator()
    .required()
    .email()
    .minLength(10);

final errors = validator.validateAll('abc');
// Returns: ['Must be a valid email address', 'Minimum length is 10']

๐ŸŽจ Optional UI Widgets #

Pre-built, customizable components for common validation UI patterns:

ValidationErrorText #

ValidationErrorText(
  errorMessage: 'Password must be at least 8 characters',
)

ValidationHintsList #

ValidationHintsList(
  hints: validator.getLiveHints(currentValue),
  showIcons: true,
  successColor: Colors.green,
  errorColor: Colors.red,
)

PasswordStrengthIndicator #

PasswordStrengthIndicator(
  password: currentPassword,
  showLabel: true,
  showSuggestions: true,
)

SmartFormField #

A complete form field with built-in error display, hint support, and smooth transitions.

SmartFormField(
  validator: SmartValidator().required().email().build(),
  smartValidator: myValidator, // Optional: for live hints
  showLiveHints: true,
  prefixIcon: Icon(Icons.email),
  suffixIcon: Icon(Icons.check),
  decoration: InputDecoration(
    labelText: 'Email Address',
    border: OutlineInputBorder(),
  ),
)

Features:

  • โœจ Animated Transitions - Errors and hints fade in/out smoothly.
  • ๐ŸŽจ Custom Icons - Support for prefixIcon and suffixIcon.
  • ๐Ÿ› ๏ธ Convenience - Manages its own TextEditingController if none provided.

๐Ÿ“ฑ Platform Support #

Smart Form Validator works on all Flutter platforms:

  • โœ… Android
  • โœ… iOS
  • โœ… Web
  • โœ… Windows
  • โœ… macOS
  • โœ… Linux

๐ŸŽ“ Examples #

The package includes 5 complete example apps demonstrating all features:

  1. Basic Form - Simple login with email and password
  2. Advanced Form - Registration with live hints and password strength
  3. Custom Validation - Custom rules for username format and age validation
  4. Async Validation - Username availability check with debouncing
  5. Controller-Based - Programmatic validation without forms

Run the Examples #

cd example
flutter run

Or try on web:

cd example
flutter run -d chrome

๐Ÿ’ก Usage Patterns #

TextFormField(
  validator: SmartValidator().required().email().build(),
)

Standalone Validation #

final validator = SmartValidator().required().email();
final error = validator.build()('user@example.com');  // null if valid

With State Management #

// In your Bloc/Provider/Controller
final emailValidator = SmartValidator().required().email();

void validateEmail(String email) {
  final error = emailValidator.build()(email);
  if (error != null) {
    emit(ValidationError(error));
  }
}

๐Ÿ”ง API Reference #

SmartValidator #

Main validator class with chainable methods.

SmartValidator([Map<String, dynamic>? context])

Methods:

  • required({String? message}) - Required field validation
  • email({String? message}) - Email format validation
  • minLength(int length, {String? message}) - Minimum length
  • maxLength(int length, {String? message}) - Maximum length
  • number({num? min, num? max, bool allowDecimals, String? message}) - Number validation
  • uppercase({int minCount, String? message}) - Uppercase letter requirement
  • lowercase({int minCount, String? message}) - Lowercase letter requirement
  • matchField(String key, String name, {String? message}) - Field matching
  • custom(Function validator, {String? message, Function? hintsGenerator}) - Custom rule
  • build() - Build the validator function
  • validateAll(String? value) - Get all validation errors
  • getLiveHints(String? value) - Get live validation hints

AsyncValidator #

Async validation with debouncing.

AsyncValidator(
  Future<ValidationResult> Function(String?) validator,
  {int debounceMilliseconds = 300,
  List<ValidationRule> syncRules = const []}
)

๐Ÿค Contributing #

Contributions are welcome! Please feel free to submit a Pull Request.

How to Contribute #

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License #

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Support #

If you find this package helpful, please:

  • โญ Star the repository
  • ๐Ÿ› Report bugs and issues
  • ๐Ÿ’ก Suggest new features
  • ๐Ÿ“ข Share with other Flutter developers

๐Ÿ‘ค Author #

Md Mahmud Hossain Ferdous

Md Mahmud Hossain Ferdous
Junior Flutter Developer



Made with โค๏ธ by MHFerdous for the Flutter community

3
likes
150
points
39
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A clean, chainable, and developer-friendly form validation package for Flutter. Build complex validation rules with minimal boilerplate using a fluent API.

Repository (GitHub)
View/report issues

Topics

#validation #form #flutter #form-validation #validator

License

MIT (license)

Dependencies

flutter

More

Packages that depend on flutter_smart_validator