如何以Xamarin形式验证电子邮件“ Entrycell”

时间:2019-07-09 10:48:36

标签: xamarin xamarin.forms

我的表格视图中有一个电子邮件条目单元格。我需要为此进行行为验证。 我如何为EntryCell做同样的事情? 我当前输入的代码如下。

/ *

public class EmailValidatorBehavior : Behavior<Entry>
{

protected override void OnAttachedTo(Entry bindable)
{
base.OnAttachedTo(bindable);
bindable.TextChanged += HandleTextChanged;
}

void HandleTextChanged(object sender, TextChangedEventArgs e)
{
var email = e.NewTextValue;

var emailpattern = @"^(?("")("".+?(?<!\\)""@)|(([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]))$";
var emailentry = sender as Entry;

if (Regex.IsMatch(email, emailpattern))
{

emailentry.BackgroundColor = Color.Transparent;
}
else
{

emailentry.BackgroundColor = Color.Red;
}
}

protected override void OnDetachingFrom(Entry bindable)
{
base.OnDetachingFrom(bindable);
bindable.TextChanged -= HandleTextChanged;
}
}

* /

2 个答案:

答案 0 :(得分:0)

也许您可以使用laber和entry自定义viewcell,然后将其添加到条目中,或者可以使用CustomRender这样(对于android的简单示例,不确定它是否满足您的需求,ios与此相似) :

[assembly: ExportRenderer(typeof(EntryCell), typeof(MyEntryCellRenderer))]
namespace App18.Droid
{
  class MyEntryCellRenderer : EntryCellRenderer
   {
    string emailpattern = @"^(?("")("".+?(?<!\\)""@)|(([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]))$";
    EditText _view;

    protected override Android.Views.View GetCellCore(Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
    {
        var cell = base.GetCellCore(item, convertView, parent, context) as EntryCellView;
        cell.EditText.AfterTextChanged += EditText_AfterTextChanged;
        return cell;
    }


    private void EditText_AfterTextChanged(object sender, Android.Text.AfterTextChangedEventArgs e)
    {
        if (Regex.IsMatch(((EditText)sender).Text, emailpattern))
        {

            ((EditText)sender).SetTextColor(Android.Graphics.Color.Green);
        }
        else
        {

            ((EditText)sender).SetTextColor(Android.Graphics.Color.Red);
        }
    }
  }
}

答案 1 :(得分:-1)

您可以将正则表达式添加到模型中的Email属性的声明之上,只有在遵守正则表达式条件的情况下,该属性才有价值。