String Constraint on compilation => abstract (?)

38 views
Skip to first unread message

Théo Sabattié

unread,
Jul 23, 2016, 8:58:13 PM7/23/16
to Haxe
Hi everyone ! 

I would like setup a type of string with a regex constraint:
~/[A-Z]*[0-9]*/i

("A1", "E2", "DA19", etc...)

I would like check validity on compilation.

I suppose we can do that with abstract type but I am not sure.

I tried that :

abstract Address(String) to String
{
    inline function new(s:String) {
        this = s;
    }
    
    @:from
    static public function fromString(s:String) {
        if (!~/[A-Z]*[0-9]*/i.match(s)) {
           throw "Invalid adress"; 
        }
        
        return new Address(s);
    }
}

But it doesn't work at compilation.

Someone have an idea?

Thanks,

Théo Sabattié.

Cambiata

unread,
Jul 24, 2016, 1:27:08 AM7/24/16
to Haxe
I guess it's a regex problem - '+' instead of '*' would restrict to 'one or many'.
Try this one, based on http://code.haxe.org/category/abstract-types/emailaddress.html

abstract Address(String) to String {
 
static var ereg = ~/[A-Z]+[0-9]+/i;
 
inline public function new(address:String) {
   
if (!ereg.match(address)) throw 'Address "$address" is invalid';
   
this = address;
 
}

 
@:from inline static public function fromString(address:String) {
   
return new Address(address);
 
}
}

The regex can be static - instantiated once instead of at every run.

Jonas

Théo Sabattié

unread,
Jul 24, 2016, 12:53:44 PM7/24/16
to Haxe
Thanks Cambiata,

I search to check validity on compilation // in IDE. 
Currently that works on runtime.

Do you know any meta build or other thing to do that?

Théo.

Jonas Malaco Filho

unread,
Jul 24, 2016, 1:20:20 PM7/24/16
to Haxe
You could try using a macro @:from function: http://try-haxe.mrcdk.com/#0fbeF

Hope that helps...

--
To post to this group haxe...@googlegroups.com
http://groups.google.com/group/haxelang?hl=en
---
You received this message because you are subscribed to the Google Groups "Haxe" group.
For more options, visit https://groups.google.com/d/optout.

Théo Sabattié

unread,
Jul 24, 2016, 2:29:32 PM7/24/16
to Haxe
Great ! Thanks a lot Jonas! :)
Reply all
Reply to author
Forward
0 new messages