Search code examples
regexvalidationemailflutter

Email validation not working in flutter display message even if email address is correct


In this code, the empty-email validation works but email-type validation does not work. Email-type validation still displays the "Invalid Email" message if a valid email address is inserted.

new TextFormField(
      decoration: new InputDecoration(
        labelText: 'Email'
      ),
      validator: (value){
        if (value.isEmpty) {
          return 'Email is required';
        }
        if(!value.contains(r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')){
          return 'Invalid Email';
        }
        return null;
      },
    )

The line that is potentially erroneous is:

if(!value.contains(r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'))

Solution

  • You can match the Regular Expression by using hasMatch method of RegExp

    Try this

       Pattern pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
       RegExp regex = new RegExp(pattern);
       if (!(regex.hasMatch(value)))
          return "Invalid Email";
    

    If you want to use .contains of String you can pass a RegExp object as argument

    if (!(value.contains(regex)))
         return "Invalid Email";