skip to Main Content

I faced with the problem of validating text fields.
Here you need to enter the date in the format dd.mm.yyyy. I also use flutter_multi_formatter package for this form.

import 'package:flutter/material.dart';
import 'package:flutter_multi_formatter/formatters/masked_input_formatter.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: StartPage());
  }
}

class StartPage extends StatelessWidget {
  const StartPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 300, horizontal: 50),
        child: TextFormField(
          onChanged: (val) {},
          keyboardType: TextInputType.number,
          decoration: const InputDecoration(hintText: 'dd.mm.yyyy'),
          inputFormatters: [MaskedInputFormatter('##.##.####')],
        ),
      ),
    );
  }
}

For example, user will start entering an incorrect date format: 32.13.2009. And I want the text with the error notification to appear below this form. Is it possible to add validation for this form if an incorrect date is entered? Maybe it’s good to parse the entered text and use conditions to compare numbers. I will be glad any help.

2

Answers


  1. I suggest you look at Flutter Form Validation doc provided by flutter itself.

    Example:

    TextFormField(
                // The validator receives the text that the user has entered.
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter some text';
                  }
                  return null;
                },
              ),
    
    Login or Signup to reply.
  2. Try below code I have try using extension:

    Extension:

    extension DateValidator on String {
      bool isValidDate() {
        final regExp = RegExp(r'^d{2}.d{2}.d{4}$');
        if (!regExp.hasMatch(this)) {
          return false;
        }
    
        final parts = this.split('.');
        final day = int.tryParse(parts[0]);
        final month = int.tryParse(parts[1]);
        final year = int.tryParse(parts[2]);
    
        if (day == null || month == null || year == null) {
          return false;
        }
        // for day validation
        if (day < 1 || day > 31) {
          return false;
        }
        // for month validation
        if (month < 1 || month > 12) {
          return false;
        }
        // for year validation 
        // for below you can choose maximum year on your need instead of DateTime.now().year
        if (year < 1900 || year > DateTime.now().year) {
          return false;
        }
        // for feb month validation
        final date = DateTime(year, month, day);
        if (date.day != day || date.month != month || date.year != year) {
          return false;
        }
        return true;
      }
    }
    

    UI:

     TextFormField(
            onChanged: (val) {},
            keyboardType: TextInputType.number,
            decoration: const InputDecoration(
              hintText: 'dd.mm.yyyy',
            ),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter a date';
              } else if (!value.isValidDate()) {
                return 'Invalid date';
              }
    
              return null;
            },
          ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search