【发布时间】:2017-08-16 05:04:48
【问题描述】:
我想为我的 Xamarin Forms 项目添加一些验证。这些是一些非常基本的内容,例如:
- 最小/最大字符串长度
- 电子邮件格式
- 密码确认
我在我的项目中使用 MVVM Light,因此,我没有在我的页面中使用代码。
我正在使用下面的代码,尝试将 Behavior 的值绑定到我的 ViewModel 中的属性。
EmailValidatorBehavior.cs:
public class EmailValidatorBehavior : 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 BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(EmailValidatorBehavior), 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;
}
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 bindable)
{
bindable.TextChanged -= HandleTextChanged;
}
}
View.xaml:
<Entry
Placeholder="E-mail"
Text="{Binding Path=User.email, Mode=TwoWay}"
Keyboard="Email">
<Entry.Behaviors>
<EmailValidatorBehavior x:Name="emailValidator" IsValid="{Binding Path=IsEmailValid, Mode=TwoWay}" />
</Entry.Behaviors>
</Entry>
ViewModel.cs:
private bool _IsEmailValid = false;
public bool IsEmailValid
{
get
{
return _IsEmailValid;
}
set
{
_IsEmailValid = value;
RaisePropertyChanged("IsEmailValid");
}
}
IsEmailValid 的值永远不会改变,即使电子邮件是正确的并且行为的 IsValid 属性变为 true。有什么问题?
提前致谢。
【问题讨论】:
-
你发现了吗?
标签: c# validation mvvm xamarin.forms