How do I validate an e-mail field in Dart?

Posted on

Question :

I created a simple project in Dart whose intention is to validate an email field when a button is clicked, showing an error message .

However, the RegExp.hasMath function is always returning false . I do not know what could be wrong.

Below is the HTML code and then Dart.

<!-- formulario.html -->
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Teste e-mail</title>
    <div class="form">
        <input type="text" id="inputEmail">
    <div class="error">
        <span id="errorMessage"></span>
    <script type="application/dart" src="validate.dart"></script>
    <script src="packages/browser/dart.js"></script>
// validate.dart
import 'dart:html';

void main(){

void verifyEmail(Event e) {
  String email = querySelector('#inputEmail').text;
  querySelector('#errorMessage').text = 
      isValidEmail(email) ? '' : 'E-mail inválido!';

bool isValidEmail(String email){
  RegExp reg = new RegExp(r"^[^@]+@[^@]+.[^@]+$");
  return reg.hasMatch(email);


Answer :

The problem here was to use the text property. in the expectation that it would return the text entered by the user. What this property does however is read content within the node, similar to Node.textContent . Note that the text of a input is always blank since the tag can not contain children.

<p>Texto <strong>aqui</strong></p>   <!-- text = "Texto aqui" -->

The correct thing is to read the value property. But for this you should have a InputElement instead of a Element , a cast needs to be done before reading the property two ways to do this:

// Explícito:
String email = (querySelector('#inputEmail') as InputElement).value;

// Implícito:
InputElement inputEmail = querySelector('#inputEmail');
String email = inputEmail.value;

You can also do cast and ignore the generated warning (avoid ignoring warnings):

String email = querySelector('#inputEmail').value;

On your isValidEmail return always false, it is correct. You were actually passing "" to it.


Leave a Reply

Your email address will not be published. Required fields are marked *