How do I validate an email field on Dart?

Asked

Viewed 550 times

5

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

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

Below follows the HTML code and then the 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);
}
  • Try reading querySelector('#inputEmail').value instead of text.

  • There is no property value in class Element returned by the method querySelector.

  • 1

    Oops. Maybe (querySelector('#inputEmail') as InputElement).value?

  • I included your solution @Guilherme. Gratefully!

  • In case there should be an answer instead of editing the question. I will write one with more details.

  • I agree, however, in this case the error found has nothing to do with the question, so I edited to include the solution. But if that has nothing to do with it, post the answer.

Show 1 more comment

1 answer

9


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

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

The correct thing is to read the property value. But for that you must have one InputElement instead of a Element, one 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 not do cast some and ignore the generated warning (avoid ignoring warnings):

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

About your isValidEmail always return false, it is correct. You were actually passing "" for him.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.