haxe Abstracts Abstracts for data validation


The following abstract defines an EmailAddress type based on the String type which will use a regular expression to validate the passed argument as an e-mail address. If the address isn't valid, an exception will be thrown.

abstract EmailAddress(String) {
  static var ereg = ~/^[\w-\.]{2,}@[\w-\.]{2,}\.[a-z]{2,6}$/i;
  inline public function new(address:String) {
    if (!ereg.match(address)) throw "EmailAddress "$address" is invalid";
    this = address.toLowerCase();

Use the abstract as follows.

var emailGood = new EmailAddress("john@doe.com");
var emailBad = new EmailAddress("john.doe.com");

Try the example on try.haxe.org.