flutter_smart_validator 0.1.1
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 #
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
prefixIconandsuffixIcon. - ๐ ๏ธ Convenience - Manages its own
TextEditingControllerif 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:
- Basic Form - Simple login with email and password
- Advanced Form - Registration with live hints and password strength
- Custom Validation - Custom rules for username format and age validation
- Async Validation - Username availability check with debouncing
- 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 #
With TextFormField (Recommended) #
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 validationemail({String? message})- Email format validationminLength(int length, {String? message})- Minimum lengthmaxLength(int length, {String? message})- Maximum lengthnumber({num? min, num? max, bool allowDecimals, String? message})- Number validationuppercase({int minCount, String? message})- Uppercase letter requirementlowercase({int minCount, String? message})- Lowercase letter requirementmatchField(String key, String name, {String? message})- Field matchingcustom(Function validator, {String? message, Function? hintsGenerator})- Custom rulebuild()- Build the validator functionvalidateAll(String? value)- Get all validation errorsgetLiveHints(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 #
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
Junior Flutter Developer
๐ Contact & Links #
- ๐ฆ Pub.dev Package
- ๐ API Documentation
Made with โค๏ธ by MHFerdous for the Flutter community