Universal Validator

pub package popularity likes pub points

A comprehensive Flutter package providing reusable form validators, smart input widgets, and formatting utilities. Reduce boilerplate code and ensure consistent validation across your Flutter applications.

✨ Features

  • 🔍 Pre-built Validators: Email, phone, password, name, PAN, GST, and more
  • 🎯 Smart Widgets: Input fields with built-in validation and formatting
  • 🌍 International Support: Phone numbers, email formats, and localization
  • Real-time Validation: Debounced validation with customizable timing
  • 🎨 Customizable: Custom error messages, validation rules, and formatting
  • 📱 Cross-platform: Works on iOS, Android, Web, and Desktop
  • 🧪 Well Tested: Comprehensive test coverage with property-based testing

📦 Installation

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

dependencies:
  universal_validator: ^1.0.0

Then run:

flutter pub get

🚀 Quick Start

Basic Validators

import 'package:universal_validator/universal_validator.dart';

// Email validation
String? emailError = EmailValidator.validate('user@example.com');
print(emailError); // null (valid)

// Phone validation (supports international formats)
String? phoneError = PhoneValidator.validate('+919876543210');
print(phoneError); // null (valid)

// Password validation
String? passwordError = PasswordValidator.validate('MySecure123!');
print(passwordError); // null (valid)

Smart Text Fields

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

class MyForm extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // Email field with built-in validation
        SmartTextField(
          fieldType: FieldType.email,
          decoration: InputDecoration(
            labelText: 'Email',
            hintText: 'Enter your email',
          ),
          onValidationChanged: (result) {
            print('Email valid: ${result.isValid}');
          },
        ),
        
        // Phone field with formatting
        SmartTextField(
          fieldType: FieldType.phone,
          decoration: InputDecoration(
            labelText: 'Phone Number',
            hintText: 'Enter phone number',
          ),
          showSuccessIndicator: true,
        ),
        
        // Password field with strength validation
        SmartTextField(
          fieldType: FieldType.password,
          decoration: InputDecoration(
            labelText: 'Password',
            hintText: 'Enter a strong password',
          ),
          obscureText: true,
        ),
      ],
    );
  }
}

📋 Supported Validators

Validator Description Example
EmailValidator RFC-compliant email validation user@domain.com
PhoneValidator International & Indian phone numbers +919876543210, 9876543210
PasswordValidator Configurable password strength MySecure123!
NameValidator Names with cultural character support John Doe, Mary-Jane
PANValidator Indian PAN card format ABCDE1234F
GSTValidator Indian GST number with checksum 22AAAAA0000A1ZC

🎯 Smart Widgets

SmartTextField

A powerful text field widget with built-in validation and formatting:

SmartTextField(
  fieldType: FieldType.email,
  enableRealTimeValidation: true,
  validationDebounce: Duration(milliseconds: 300),
  showSuccessIndicator: true,
  customErrorMessages: {
    'email': 'Please enter a valid email address',
  },
  onValidationChanged: (ValidationResult result) {
    // Handle validation state changes
    if (result.isValid) {
      print('Input is valid!');
    } else {
      print('Error: ${result.errorMessage}');
    }
  },
)

Field Types

enum FieldType {
  email,    // Email addresses
  phone,    // Phone numbers (international/Indian)
  password, // Passwords with strength validation
  name,     // Person names
  pan,      // Indian PAN cards
  gst,      // Indian GST numbers
  custom,   // Custom validation rules
}

⚙️ Advanced Configuration

Custom Password Validation

final passwordConfig = PasswordConfig(
  minLength: 12,
  requireUppercase: true,
  requireLowercase: true,
  requireNumbers: true,
  requireSpecialChars: true,
  forbiddenPasswords: ['password123', 'admin'],
);

SmartTextField(
  fieldType: FieldType.password,
  configuration: FieldConfiguration(
    parameters: {'passwordConfig': passwordConfig},
  ),
)

Custom Validation Rules

SmartTextField(
  fieldType: FieldType.custom,
  configuration: FieldConfiguration(
    customRules: [
      ValidationRule(
        name: 'minLength',
        validator: (value) => value?.length >= 5,
        errorMessage: 'Must be at least 5 characters',
        priority: 1,
      ),
      ValidationRule(
        name: 'noSpaces',
        validator: (value) => !value?.contains(' ') ?? true,
        errorMessage: 'Spaces are not allowed',
        priority: 2,
      ),
    ],
  ),
)

Input Formatting

// Phone number formatting
String formatted = PhoneFormatter.format('9876543210');
print(formatted); // "98765 43210"

// Name formatting (title case)
String formattedName = NameFormatter.format('john doe');
print(formattedName); // "John Doe"

// PAN formatting (uppercase)
String formattedPAN = PANFormatter.format('abcde1234f');
print(formattedPAN); // "ABCDE1234F"

🌍 Internationalization

Phone Number Support

// Indian numbers
PhoneValidator.validate('9876543210'); // ✅ Valid
PhoneValidator.validate('+919876543210'); // ✅ Valid

// US numbers
PhoneValidator.validate('+12345678901'); // ✅ Valid

// UK numbers
PhoneValidator.validate('+441234567890'); // ✅ Valid

Custom Error Messages

SmartTextField(
  fieldType: FieldType.email,
  customErrorMessages: {
    'email': 'कृपया एक वैध ईमेल पता दर्ज करें', // Hindi
    'required': 'यह फ़ील्ड आवश्यक है',
  },
)

🧪 Testing

The package includes comprehensive property-based tests to ensure reliability:

# Run all tests
flutter test

# Run specific validator tests
flutter test test/email_validator_property_test.dart
flutter test test/phone_validator_property_test.dart

📱 Platform Support

Platform Support
Android
iOS
Web
macOS
Windows
Linux

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Development Setup

  1. Fork the repository
  2. Clone your fork: git clone https://github.com/your-username/universal_validator.git
  3. Create a feature branch: git checkout -b feature/amazing-feature
  4. Make your changes and add tests
  5. Run tests: flutter test
  6. Commit your changes: git commit -m 'Add amazing feature'
  7. Push to the branch: git push origin feature/amazing-feature
  8. Open a Pull Request

📄 License

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

🙏 Acknowledgments

  • Thanks to all contributors who have helped improve this package
  • Inspired by the need for consistent form validation in Flutter applications
  • Built with ❤️ for the Flutter community

📞 Support


Made with ❤️ by Your Name

Libraries

universal_validator
Universal Validator - A comprehensive Flutter package for form validation