How to restrict flutter Textfield or TextFormField to accept only english language?

Viewed 841

How to restrict flutter Textfield or TextFormField to accept only english language ?? No other language should be allowed to enter.

3 Answers

Try with this

TextField(
  inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp("^[\u0000-\u007F]+\$"))
    ])

Or you can try with this if you want only english character.

 TextField(
   inputFormatters: [
            FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]"))
       ])
TextField(
    inputFormatters: <TextInputFormatter>[
       FilteringTextInputFormatter.allow(RegExp('[a-z A-Z 0-9]'))
    ],
)

You can use regular expressions of english

bool validEnglish(String value) { 
  RegExp regex = RegExp(r'/^[A-Za-z0-9]*$'); 
  return (!regex.hasMatch(value)) ? false : true; 
}

TextFormField(
              decoration: InputDecoration(
                hintText: 'Enter text',
              ),
              textAlign: TextAlign.center,
               validator: (text) {
                if (text == null || text.isEmpty || !validEnglish(text)) {
                  return 'Text is empty or invalid' ;
                }
                return null;
              },
            )



    
Related