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

5

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>

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

void main(){
  querySelector('#submit').onClick.listen(verifyEmail);
}

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);
}
    
asked by anonymous 08.01.2014 / 02:25

1 answer

7

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.

    
09.01.2014 / 14:34