Maybe you should change IsValid variable to property like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Text.RegularExpressions;
namespace LoginUser
{
public class ValidationBehavior: Behavior<Entry>
{
const string pwRegex = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[^da-zA-Z]).{8,15}$";
static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(ValidationBehavior), false);
public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
private set { base.SetValue(IsValidPropertyKey, value); }
}
protected override void OnAttachedTo(Entry bindable)
{
bindable.TextChanged += HandleTextChanged;
}
private void HandleTextChanged(object sender, TextChangedEventArgs e)
{
IsValid= (Regex.IsMatch(e.NewTextValue, pwRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
}
protected override void OnDetachingFrom(Entry bindable)
{
bindable.TextChanged -= HandleTextChanged;
}
}
}
Another error is also your regular expression, try the following:
^(?=.*[a-z])(?=.*[A-Z])(?=.*d).{8,15}$
If you also want to require at least one special character (which is probably a good idea), try this:
^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[^da-zA-Z]).{8,15}$
With my sample you get like this:
With password: 123456
With password: AbcDe12!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…