Home > OS >  Sanitizing & Validating user inputs in flutter TextFormField
Sanitizing & Validating user inputs in flutter TextFormField

Time:10-27

I'm looking for some easy technique for sanitizing and validating user input in TextFormField

With that I would also like to maintain structure of the code and readability.

Is there any solution where I can execute series of Sanitizers (eg. Trim, ToLowerCase) and Validators (eg. Value is Required, Valid Email) on an input in TextFormField?

Thank You

CodePudding user response:

There is a package on pub.dev validation_chain

Which provides useful APIs for Sanitizing and Validating different forms of Data (May be a TextInput from a user or Map<dynamic, dynamic> data from request / response body)

We will see example of using SanitizationChain & ValidationChain APIs with TextFormField in Flutter.

However, this package also provides more APIs covering different use cases. Which can also be used with Server-Side / CLI-based Dart apps. (you can refer package documentation for more details.)

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

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  App({super.key});

  final _formKey = GlobalKey<FormState>();
  final _email = TextEditingController(text: '    [email protected]    ');

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Sanitization Chain Example'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Form(
              key: _formKey,
              child: TextFormField(
                controller: _email,
                decoration: const InputDecoration(labelText: 'Email'),

                validator: ValidationChain(
                  [compulsory, tooShort, tooLong],
                ).validate,
                onSaved: (value) {
                  _email.text = SanitizerChain(
                        [trim, lowerCase],
                      ).sanitize(value) ??
                      '';
                },

              ),
            ),
            const SizedBox(height: 32),
            ElevatedButton(
              child: const Text('Sanitize'),
              onPressed: () {

                _formKey.currentState!.save();
                _formKey.currentState!.validate();

              },
            ),
          ],
        ),
      ),
    );
  }

  /* -----Utility functions----- */

  String? trim(String? value) {
    return value?.trim();
  }

  String? lowerCase(String? value) {
    return value?.toLowerCase();
  }

  String? compulsory(String? value) {
    return (value?.isEmpty ?? true) ? 'Required' : null;
  }

  String? tooShort(String? value) {
    return value != null && value.length < 5 ? 'Too Short' : null;
  }

  String? tooLong(String? value) {
    return value != null && value.length > 10 ? 'Too Long' : null;
  }

}
  • Related