[SOLVED] how can I force user to enter the first letter is number 1

Issue

This Content is from Stack Overflow. Question asked by Youssif Nasser

I have a textfield that should enter an ID, I need to force the user to enter the first number to be (1)
also, can anyone suggest how to learn RegExp package.. I find it solve most of this problems

import 'package:flutter/material.dart';

class TestDate extends StatelessWidget {
  TestDate({Key? key}) : super(key: key);

  var controller = TextEditingController();
  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: EdgeInsets.all(40),
        child: Form(
          key: formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextFormField(
                controller: controller,
                decoration: InputDecoration(border: OutlineInputBorder()),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter some text';
                  }
                  return null;
                },
              ),
              ElevatedButton(
                onPressed: () {
                  if (formKey.currentState!.validate()) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('Processing Data')),
                    );
                  }
                },
                child: const Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}



Solution

It depends on what you really want.

Should the user have the freedom to write the text how he wants and you just want to validate at the end? Then update your validator callback:

validator: (value) {
  if (value == null || value.isEmpty) {
    return 'Please enter some text';
  } else if (!value.startsWith("1")) {
    return 'Text needs to start with \'1\'';
  }
  return null;
},

However, if you want to force the user to always give a text which starts with 1, then you can create a class which extends TextInputFormatter:

class MyTextInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    if (!newValue.text.startsWith("1")) {
      return oldValue;
    }
    return newValue;
  }
}

Then:

TextFormField(
  ...
  inputFormatters: [
    MyTextInputFormatter()
  ],
),

By the way: If you don’t need the controller, then don’t instantiate one. If you do, then don’t forget to dispose it.


This Question was asked in StackOverflow by Youssif Nasser and Answered by TripleNine It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?