### Example Validation Error Output Source: https://pub.dev/packages/ez_validator This is an example of the output when validation fails. The 'errors' map will contain field names and their corresponding error messages. ```json { "password": "Minimum six characters, at least one letter, one number and one special character", "age": "The field must be greater than or equal to 18" } ``` -------------------------------- ### Getting Transformed Values Source: https://pub.dev/packages/ez_validator Demonstrates how to retrieve transformed values after validation. The `.build(applyTransform: true)` option ensures transformations are applied. ```dart final validator = EzValidator() .transform((value) => value.trim()) .minLength(3) .build(applyTransform: true); final result = validator(" hello "); // result = "hello" (transformed value) final error = validator(" a "); // error = "Input must be at least 3 characters..." (error message) ``` -------------------------------- ### Schema-Level Transformation Source: https://pub.dev/packages/ez_validator Apply transformations at the schema level using `applyTransform: true`. This example transforms the length of the 'name' field to a string. ```dart final schema = EzSchema.shape( { 'name': Ez().transform((v) => v.length().toString()).minLength(3), 'age': Ez().required(), }, applyTransform: true, ); final (data, errors) = schema.validateSync({ 'name': 'Ehab', 'age': 25, }); print(data); // print => {"name": "4" , "age": 25} ``` -------------------------------- ### Define Custom Arabic Locale for EzValidator Source: https://pub.dev/packages/ez_validator Implement the EzLocale interface to provide custom error messages in Arabic. This example shows how to define messages for required fields and email validation. ```dart class ArLocale implements EzLocale { const ArLocale(); // Implement all required methods with Arabic error messages @override String minLength(String v, int n, [String? label]) => '${label ?? 'الحقل'} يجب أن يحتوي على الأقل $n أحرف'; // ... other method implementations ... @override String required([String? label]) => '${label ?? 'الحقل'} مطلوب'; // Example implementation for a valid email @override String email(String v, [String? label]) => '${label ?? 'الحقل'} ليس بريدًا إلكترونيًا صحيحًا'; // ... further implementations for other methods ... } ``` -------------------------------- ### Import ez_validator in Dart Code Source: https://pub.dev/packages/ez_validator/install Import the ez_validator package into your Dart files to start using its validation functionalities. ```dart import 'package:ez_validator/ez_validator.dart'; ``` -------------------------------- ### OR Type Validation with .union Source: https://pub.dev/packages/ez_validator Utilize `.union` to create validators that accept one of several possible types. This example allows a field to be either a String or a number. ```dart final schema = EzSchema.shape({ 'mixedField': EzValidator().union([ EzValidator().isType(String), EzValidator().isType(num) ]) }); schema.catchErrors({'mixedField': 'test'}) // passed schema.catchErrors({'mixedField': true}) // not passed ``` -------------------------------- ### Custom JSON Validation with addMethod Source: https://pub.dev/packages/ez_validator Define custom validation logic using the addMethod function. Each method takes the value and returns null for success or an error message for failure. This example validates specific keys and array elements within a JSON structure. ```dart final checkJson = EzValidator>() .addMethod((v) => v?['foo'] == 'bar' ? null : 'Foo should be bar') .addMethod((v) => v?['bar'] == 'Flutter' ? null : 'Bar should be Flutter') .addMethod((v) => v?['items'][0] == 'a' ? null : 'First item should be a') .build(); final errors = checkJson({ 'foo': 'bar', 'bar': 'Flutter', 'items': ['a', 'b', 'c'] }); print(errors); // Outputs the validation errors, if any ``` -------------------------------- ### Array and Nested Schema Validation Source: https://pub.dev/packages/ez_validator Validate lists of objects using `.arrayOf` and nested schemas using `.schema`. This example validates a list of students within a classroom, ensuring each student meets age and name requirements. ```dart // Define a schema for individual student validation final EzSchema studentSchema = EzSchema.shape({ "name": EzValidator().required(), "age": EzValidator().min(18, "Students must be at least 18 years old."), }); // Validator for validating a list of students final EzValidator>> studentsListValidator = EzValidator>>() .required() .arrayOf>( EzValidator>().schema(studentSchema), ); // Define a schema for a classroom, which includes a list of students final EzSchema classroomSchema = EzSchema.shape({ "className": EzValidator().required(), "students": studentsListValidator, }); var result = classroomSchema.validateSync({ "className": "Advanced Mathematics", "students": [ {"name": "John Doe", "age": 20}, {"name": "Jane Smith", "age": 17}, // ---> This will cause a validation error ], }); print(result.$2); // {students: {"age":"Students must be at least 18 years old."}} ``` -------------------------------- ### Validate Nested Data with EzValidator Schema Source: https://pub.dev/packages/ez_validator Perform synchronous validation on a complex, nested data structure using the defined `userProfileSchema`. This example shows how missing nested fields are handled and demonstrates the output of validated data and errors. ```dart final (data, errors) = userProfileSchema.validateSync({ 'firstName': 'John', 'lastName': 'Doe', 'email': 'john.doe@example.com', 'age': 30, 'contactDetails': { 'mobile': '+12345678901', }, 'address': { 'street': '123 Main St', 'city': 'Anytown', 'state': 'Anystate', 'zipCode': 12345, 'country': { }, // I will not define the country }, 'employment': { 'current': 'Current Company', 'previous': { 'companyName': 'Previous Company', 'position': 'Previous Position', 'years': 5, }, }, }); print(data); // Result of displayed data will contain country with default values // { // firstName: John, // lastName: Doe, // email: john.doe@example.com, // age: 30, // contactDetails: { mobile: +12345678901, landline: null }, // address: // { // street: 123 Main St, // city: Anytown, // state: Anystate, // zipCode: 12345, // country: // { name: TUNISIA, code: null, continent: { name: null, code: null } }, // }, // employment: // { // current: Current Company, // previous: // { // companyName: Previous Company, // position: Previous Position, // years: 5, // }, // }, // } // print(errors) // {address: {country: {code: The field is required, continent: {name: The field is required, code: The field is required}}}} ``` -------------------------------- ### Dynamic Validation with .dependsOn Source: https://pub.dev/packages/ez_validator Employ `.dependsOn` to dynamically adjust field validation rules based on the value of another field. This example validates passenger numbers differently for SUVs versus other car types. ```dart final EzSchema carValidationSchema = EzSchema.shape({ "car_type": EzValidator(defaultValue: CarType.suv).required(), "passangers_number": EzValidator().dependsOn( condition: (ref) => ref!["car_type"] == CarType.suv, then: EzValidator().required().max(6, 'Max 6 passangers'), orElse: EzValidator().required().max(4, 'Max 4 passangers'), ), }); final errors = carValidationSchema.catchErrors({ "car_type": CarType.suv, "passangers_number": 7, }); print(errors); // {'passangers_number' : 'Max 6 passangers'} ``` -------------------------------- ### Flutter App Main Entry Point Source: https://pub.dev/packages/ez_validator/example Sets up the main application widget and theme. This is the entry point for the Flutter app. ```dart // ignore_for_file: avoid_print import 'dart:io'; import 'package:ez_validator/ez_validator.dart'; import 'package:ez_validator_example/error_widget.dart'; import 'package:ez_validator_example/fr.dart'; // import 'package:ez_validator_example/french_locale.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; void main() { /// set this in the main to set your custom locale runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'exemple', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'EzValidator Exemple'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, this.title}) : super(key: key); final String? title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { Map form = {"number": '5', "pos": '-5', 'file': File('')}; Map errors = {}; EzSchema formSchema = EzSchema.shape( { "email": EzValidator(label: "l'email").required().email(), "password": EzValidator(label: 'le mot de passe').required().minLength(8), "age": EzValidator(label: 'l\'age').required().number().max(18), "birth_year": EzValidator().required().number().min(2017), "file": EzValidator().required().addMethod((file) => file != null && file .lastAccessedSync() .isAfter(DateTime.now().subtract(const Duration(days: 1)))), "date": EzValidator(defaultValue: DateTime(2018)).required().date(), }, ); void validate() { /// wrap your validation method with try..catch when you add the /// identicalKeys clause to your schema try { final res = formSchema.validateSync(form); setState(() { errors = res.$2; }); print(res.$1); errors.forEach((key, value) { print('$key ===> $value'); }); } catch (e) { print(e); Fluttertoast.showToast( msg: "Missing fields input", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0, ); } } InputDecoration _getInputDecoration(IconData icon, String label) { return InputDecoration( prefixIcon: Icon(icon), border: InputBorder.none, fillColor: const Color(0xfff3f3f4), filled: true, hintText: label, ); } _onChange(String name, dynamic value) { form[name] = value; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title as String), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Container( color: Colors.black12, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 25.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ TextField( onChanged: (value) => _onChange('email', value), decoration: _getInputDecoration(Icons.email, "Email"), ), ErrorWIdget(name: errors['email']), const SizedBox(height: 10.0), TextField( onChanged: (value) => _onChange('password', value), decoration: _getInputDecoration(Icons.password, "Password"), ), ErrorWIdget(name: errors['password']), const SizedBox(height: 10.0), TextField( keyboardType: TextInputType.number, onChanged: (value) => _onChange('age', value), decoration: _getInputDecoration( Icons.supervised_user_circle_outlined, "Age"), ), ErrorWIdget(name: errors['age']), const SizedBox(height: 10.0), TextField( ``` -------------------------------- ### Form Input and Validation with EzValidator Source: https://pub.dev/packages/ez_validator/example This snippet shows how to set up input fields for a birth year and a submit button. It utilizes EzValidator for error display and includes a button to change the locale. ```dart keyboardType: TextInputType.number, onChanged: (value) => _onChange('birth_year', int.tryParse(value)), decoration: _getInputDecoration( Icons.date_range_outlined, "Birth Year"), ), ErrorWIdget(name: errors['birth_year']), const SizedBox(height: 10.0), MaterialButton( onPressed: validate, color: Colors.white, highlightColor: Colors.red, child: const Text("Submit"), ), MaterialButton( onPressed: () { EzValidator.setLocale(const FrLocale()); }, color: Colors.white, highlightColor: Colors.red, child: const Text("Fr Locale"), ) ], ), ), ), ), ], ), ), ); } } ``` ``` -------------------------------- ### Add ez_validator to pubspec.yaml Source: https://pub.dev/packages/ez_validator/install This is how the ez_validator dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: ez_validator: ^0.3.7 ``` -------------------------------- ### Define User Schema with EzValidator Source: https://pub.dev/packages/ez_validator Create a schema using EzSchema.shape, associating each field with an EzValidator and defining its validation rules like required, email format, minimum length, and date constraints. ```dart final EzSchema userSchema = EzSchema.shape( { "email": EzValidator(label: "Email").required().email(), "password": EzValidator(label: 'Password').required().minLength(8), 'date': EzValidator() .required() .date() .minDate(DateTime(2019)) .maxDate(DateTime(2025)), }, ); ``` -------------------------------- ### Define Complex Nested User Profile Schema Source: https://pub.dev/packages/ez_validator Create a detailed validation schema for a user profile, including nested objects for contact details, address, and employment history. Default values and optional fields are demonstrated. ```dart final EzSchema userProfileSchema = EzSchema.shape({ "firstName": EzValidator().required(), "lastName": EzValidator().required(), "email": EzValidator().required().email(), "age": EzValidator().min(18).max(100), 'contactDetails': EzSchema.shape({ 'mobile': EzValidator() .required() .matches(RegExp(r'^\+\d{10,15}$'), 'Invalid phone number'), 'landline': EzValidator(optional: true), }), 'address': EzSchema.shape({ 'street': EzValidator().required(), 'city': EzValidator().required(), 'state': EzValidator().required(), 'zipCode': EzValidator().required(), 'country': EzSchema.shape({ 'name': EzValidator(defaultValue: 'TUNISIA').required(), 'code': EzValidator().required(), 'continent': EzSchema.shape({ 'name': EzValidator().required(), 'code': EzValidator().required(), }) }), }), 'employment': EzSchema.shape({ 'current': EzValidator(optional: true), 'previous': EzSchema.shape({ 'companyName': EzValidator().required(), 'position': EzValidator().required(), 'years': EzValidator().min(1).max(50), }), }), }); ``` -------------------------------- ### Add EzValidator Dependency Source: https://pub.dev/packages/ez_validator Add EzValidator to your pubspec.yaml file to include it in your project dependencies. Use 'any' for the latest version or specify a version number. ```yaml dependencies: ez_validator: any # or the latest version on Pub ``` -------------------------------- ### Add ez_validator to Flutter Project Source: https://pub.dev/packages/ez_validator/install Use this command to add the ez_validator package as a dependency in your Flutter project. ```bash $ flutter pub add ez_validator ``` -------------------------------- ### Add ez_validator to Dart Project Source: https://pub.dev/packages/ez_validator/install Use this command to add the ez_validator package as a dependency in your Dart project. ```bash $ dart pub add ez_validator ``` -------------------------------- ### List (Array) Validations Source: https://pub.dev/packages/ez_validator Provides methods for validating list or array data. ```APIDOC ## .listOf(Type type, [String? message]) ### Description Validates that each element in the list is of the specified `type`. It iterates through the list and checks if each item matches the given type. ### Parameters #### Path Parameters - **type** (Type) - Required - The expected type for each element in the list. - **message** (String?) - Optional - Custom error message. ``` ```APIDOC ## .oneOf(List items, [String? message]) ### Description Checks if the value is one of the specified items in the list. It is useful for ensuring a value is among a predefined set of options. ### Parameters #### Path Parameters - **items** (List) - Required - The list of allowed items. - **message** (String?) - Optional - Custom error message. ``` ```APIDOC ## .notOneOf(List items, [String? message]) ### Description Ensures that the value is not one of the specified items in the list. This is the opposite of `.oneOf` and is used to exclude certain values. ### Parameters #### Path Parameters - **items** (List) - Required - The list of disallowed items. - **message** (String?) - Optional - Custom error message. ``` -------------------------------- ### Date Validations Source: https://pub.dev/packages/ez_validator Provides methods for validating date values. ```APIDOC ## .date([String? message]) ### Description Checks if the value is a valid date. If the value is a `DateTime` object or can be parsed into a `DateTime`, the validation passes. ### Parameters #### Path Parameters - **message** (String?) - Optional - Custom error message. ``` ```APIDOC ## .minDate(DateTime date, [String? message]) ### Description Ensures the date value is not earlier than the specified minimum date. If the value is a `DateTime` object and is equal to or after the provided `date`, the validation passes. ### Parameters #### Path Parameters - **date** (DateTime) - Required - The minimum date to compare against. - **message** (String?) - Optional - Custom error message. ``` ```APIDOC ## .maxDate(DateTime date, [String? message]) ### Description Ensures the date value is not later than the specified maximum date. If the value is a `DateTime` object and is equal to or before the provided `date`, the validation passes. ### Parameters #### Path Parameters - **date** (DateTime) - Required - The maximum date to compare against. - **message** (String?) - Optional - Custom error message. ``` -------------------------------- ### Conditional Validation and Transformation Source: https://pub.dev/packages/ez_validator Use `.transform` to clean input data before validation and `.when` to conditionally validate a field based on another field's value. Ensure password fields are at least 8 characters long and match. ```dart final EzSchema schema = EzSchema.shape({ // Use .transform to trim whitespace before validating the name "name": EzValidator() .transform((value) => value.trim()) .minLength(3, "Name must be at least 3 characters long."), // Use .when to validate confirmPassword based on the password field "password": EzValidator() .minLength(8, "Password must be at least 8 characters long."), "confirmPassword": EzValidator().when( "password", (confirmValue, [ref]) => confirmValue == ref?["password"] ? null : "Passwords do not match", ) }); var result = schema.validateSync({ "name": " John ", "password": "password123", "confirmPassword": "password123", }); print(result); // Should be empty if no validation errors ``` -------------------------------- ### Validate Data with validateSync Source: https://pub.dev/packages/ez_validator The validateSync method validates data and returns both the processed data and any validation errors simultaneously. The processed data may include default values defined in the schema. ```dart final (data, errors) = userSchema.validateSync({ 'email': 'example@domain.com', 'password': '12345678', 'date': DateTime.now(), }); print(data); // Processed data print(errors); // Validation errors ``` -------------------------------- ### Strict Schema Validation with `noUnknown` Source: https://pub.dev/packages/ez_validator Enforce strict validation by disallowing unknown fields in the input data using `noUnknown: true`. This ensures that only fields defined in the schema are accepted. ```dart final EzSchema strictSchema = EzSchema.shape( { 'email': EzValidator().required().email(), 'password': EzValidator().required(), 'username': EzValidator().required(), }, noUnknown: true, // Disallow unknown fields fillSchema: false, // Do not fill missing fields ); final Map dataWithUnknown = { 'email': 'test@email.com', 'password': 'password', 'age': 30, // Unknown field }; final (_, errors) = strictSchema.validateSync(dataWithUnknown); print(errors) // {age: is not defined in the schema} ``` -------------------------------- ### Validate Data with catchErrors Source: https://pub.dev/packages/ez_validator Use the catchErrors method on your schema to validate a data object. It returns a map of validation errors, with field names as keys and error messages as values. An empty map indicates successful validation. ```dart final errors = userSchema.catchErrors({ 'email': 'example@domain.com', 'password': '12345678', 'date': DateTime.now(), }); print(errors); ``` -------------------------------- ### Set Custom Locale in EzValidator Source: https://pub.dev/packages/ez_validator Configure EzValidator to use the newly created custom locale by calling the `setLocale` method with an instance of the custom locale. ```dart EzValidator.setLocale(const ArLocale()); ``` -------------------------------- ### Boolean Validation Source: https://pub.dev/packages/ez_validator Validates whether the value is a boolean. ```APIDOC ## .boolean([String? message]) ### Description Validates whether the value is a boolean (`true` or `false`). This method checks the data type of the value and ensures it is strictly a boolean. ### Parameters #### Path Parameters - **message** (String?) - Optional - Custom error message. ``` -------------------------------- ### Email Validation in TextFormField Source: https://pub.dev/packages/ez_validator Use EzValidator to apply required and email format validation to a TextFormField. Error messages appear below the field if validation fails. ```dart TextFormField( validator: EzValidator() .required() .email() .build(), decoration: InputDecoration(labelText: 'Email'), ), ``` -------------------------------- ### Number Validation Source: https://pub.dev/packages/ez_validator Checks if the value is not a number. ```APIDOC ## .notNumber([String? message]) ### Description Checks if the value is not a number. ### Parameters #### Path Parameters - **message** (String?) - Optional - Custom error message. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.