How to validate that a text field doesn't contain a whitespace in flutter?

Viewed 40

How to validate that a text field doesn't contain a whitespace in flutter? I'm trying to show it on a dialogue

if (_descriptionController2.text.isEmpty) { EasyLoading.showError('Please write a review!');

like this one but i don't know what should i write in the if statement.

4 Answers

try validator work for me here is my code

validator: (value) {
                    if (value == null || value.isEmpty) {
                      return '*Required';
                    }
                    return null;
                  },

here is another one only letters

 validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Please enter your first name';
                              } else if (!isAlpha(value)) {
                                return 'Only Letters Please';
                              }
                              return null;

also you can use .trim()

Add the following to check for whitespace

if (RegExp(r"\s").hasMatch(_descriptionController2.text)) {
      EasyLoading.showError('Text contains whitespace!')
    } 

You can create function and achieve your desire ^_^

here, val is your _descriptionController2.text

bool hasSpace(String? val) {
    if (val != null && val.contains(' ')) {
      return true;
    } else
      return false;
  }

I always use Form and Validator for this kinda scenario.

    final _formKey = GlobalKey<FormState>();
    @override
      Widget build(BuildContext context) {
        // Build a Form widget using the _formKey created above.
        return Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
      validator: (value) {
        if (value == null || value.isEmpty) {
          return 'Please enter some text';
        }
        return null;
      },
    ),
ElevatedButton(
  onPressed: () {
    // Validate returns true if the form is valid, or false otherwise.
    if (_formKey.currentState!.validate()) {
      // If the form is valid, display a snackbar. In the real world,
      // you'd often call a server or save the information in a database.
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Processing Data')),
      );
    }
  },
  child: const Text('Submit'),
),
            ],
          ),
        );
      }
Related