Skip to content

Instantly share code, notes, and snippets.

@roshanchaminda
Last active December 6, 2018 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roshanchaminda/0c9046712f3c44f3aede395413d50299 to your computer and use it in GitHub Desktop.
Save roshanchaminda/0c9046712f3c44f3aede395413d50299 to your computer and use it in GitHub Desktop.
public class EmailValidator : Behavior<Entry>
{
const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\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]))$";
public static readonly BindableProperty IsValidProperty = BindableProperty.Create("IsValid", typeof(bool), typeof(EmailValidator), false);
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
private set { base.SetValue(IsValidProperty, value); }
}
protected override void OnAttachedTo(Entry entry)
{
entry.TextChanged += HandleTextChanged;
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry entry)
{
entry.TextChanged -= HandleTextChanged;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment