dinsdag 24 juni 2014

Email Validation

Introduction

I was strugling with the apache commons email validator. This litle baby was not working according the specs they gave me. After a while I gave up on that and descided against my own rules to build it myself. What I mean with against my own rules is: Dont build if it is out there in a proper library. But in this case I had an exception. 

The best way to solve this issue was to use a regular expression. Not my favorite but mighty handy when you need them. 

Solution:

The scary part:

For those who have no experience with R.E. this might look like cursing in a comic :).

"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]+)$";

Lets analyze this:First lets have a look at the structure and later on we spill some information about the details.
The first thing you might notice in the structure are blocks like these [_A-Za-z0-9-\\+]+the A-Z, a-z or 0-9 this means that it contains an character in capitals (A-Z), or in non-capitals(a-z)or digits from 0-9. if the notation is like:[_A-Za-z0-9] It will only search for one character each.if you add a + it means iterate till you can find no more.if you add {2} or {2,5} instead of a + it means only 2 characters or from 2 to 5 characters.
In the case of the email validator you also need one .(dot) and one @ as you can see they are not followed by the annotations I described to iterate for more. 
Some of the details:
^ the carrot sign before the brackets means "Starts with" So in this case It can be a multiple underscores, characters or numbers.
The ^ inside the brackets means not like [^A-Z] everything but capitals.
The * is the same as +  occurs 1 or more times (iteration).
The $ checks if the end of line is following. 

Conclusion:

It still looks like cursing in a comic or something that gives you an headache. But it is the way forward if you want to check a string on patterns. This whole exercise is useless without execution. So you still need to use the Pattern and Matcher class (Examples all over the internet).
Or use the String.matches method. Will do two.

Have fun! 

Geen opmerkingen:

Een reactie posten