bitwarden-android/src/App/Behaviors/EmailValidationBehavior.cs

40 lines
1.5 KiB
C#
Raw Normal View History

2016-05-02 09:52:09 +03:00
using System;
using System.Text.RegularExpressions;
using Xamarin.Forms;
namespace Bit.App.Behaviors
{
public class EmailValidationBehavior : Behavior<Entry>
{
private 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]))$";
private static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(EmailValidationBehavior), false);
public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
public bool IsValid
{
get { return (bool)GetValue(IsValidProperty); }
private set { SetValue(IsValidPropertyKey, value); }
}
2016-05-04 02:49:49 +03:00
protected override void OnAttachedTo(Entry entry)
2016-05-02 09:52:09 +03:00
{
2016-05-04 02:49:49 +03:00
entry.TextChanged += HandleTextChanged;
base.OnAttachedTo(entry);
2016-05-02 09:52:09 +03:00
}
void HandleTextChanged(object sender, TextChangedEventArgs e)
{
IsValid = Regex.IsMatch(e.NewTextValue, EmailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
((Entry)sender).BackgroundColor = IsValid ? Color.Default : Color.Red;
}
2016-05-04 02:49:49 +03:00
protected override void OnDetachingFrom(Entry entry)
2016-05-02 09:52:09 +03:00
{
2016-05-04 02:49:49 +03:00
entry.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(entry);
2016-05-02 09:52:09 +03:00
}
}
}