Xamarin – Validate email with a value converter

So I wrote this quite a while ago to check an email address using regex and just decided to apply it to validation like so…

  public class EmailValidation
    {
        const string emailRegex = @"^(?("")("".+?(?&lt;!\\)&quot;&quot;@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&amp;&#039;\*\+/=\?\^`\{\}\|~\w])*)(?<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt;=[0-9a-z])@))&quot; +
        @&quot;(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$&quot;;

        public static bool IsEmailValid(string email)
        {
            return (Regex.IsMatch(email, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
        }
    }

Then I consume it like so…


  public class EmailValidConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var s = value as string;
            try
            {
                if (string.IsNullOrEmpty(s))
                {
                    return "YOUR BAD / FAIL IMAGE HERE";
                }
                else if (EmailValidation.IsEmailValid(s))
                {
                    return "YOUR GOOD / PASS IMAGE HERE";
                }
                else
                {
                    return "YOUR BAD / FAIL IMAGE HERE";
                }

            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached) Debug.WriteLine(ex.Message);
                return "YOUR BAD / FAIL IMAGE HERE";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

After that it’s just a standard value converter in XAML…

Here is another way using Fody

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s