xamarin_如何实现声明性Xamarin表单验证

xamarin

by Ameer Jhan

通过阿米尔·詹(Ameer Jhan)

如何实现声明性Xamarin表单验证 (How to implement declarative Xamarin form validation)

If you have an existing Xamarin.Forms codebase and want to add validation without affecting your code behind or view model, then this is for you. ?

如果您具有现有的Xamarin.Forms代码库,并且想要添加验证而不影响您的代码背后或视​​图模型,那么这是适合您的。 ?

是什么让我写这篇文章? (What made me write this article?)

Our team designed and developed a Xamarin mobile app with multiple forms with zero validations, since we had less time and we were okay with back end validations alone.

我们的团队设计和开发了一种Xamarin移动应用程序,该应用程序具有多种形式且零验证,因为我们的时间更少,而且我们可以单独进行后端验证。

As time passed our need to add front end validation grew with the app. So we decided to add validations without affecting our code behind or view model. There were no articles to help us with this strategy, so I decided to write one.

随着时间的流逝,我们对添加前端验证的需求随着应用程序的增长而增长。 因此,我们决定添加验证,而不会影响我们的代码背后或视​​图模型。 没有文章可以帮助我们实现这一策略,所以我决定写一篇。

先决条件 (Prerequisites)

I assume that you are comfortable with Xamarin Behaviors. If not, please read the below documentation — it is very simple and straightforward.

我认为您对Xamarin Behaviors感到满意。 如果没有,请阅读以下文档-它非常简单明了。

Xamarin.Forms Behaviors - XamarinBehaviors lets you add functionality to user interface controls without having to subclass them. Behaviors are written…docs.microsoft.com

Xamarin.Forms行为-Xamarin行为 使您可以向用户界面控件添加功能,而不必对其进行子类化。 行为被写成…… docs.microsoft.com

我们最终会得到什么 (What we will end up with)

The result will be highly readable and declarative validations on the xaml, keeping the code behind and view model away from validation!

结果将是在xaml上具有高度可读性和声明性的验证,从而使代码保持在后面并使视图模型远离验证!

注意事项 (Things to note)

Whenever the code is too long to digest in a single explanation, I will break it into multiple sections and will use three ellipses() in place of code from previous or upcoming sections.

每当代码太长而无法在一个说明中进行消化时,我都会将其分为多个部分,并使用三个省略号( )代替上一部分或下一部分的代码。

那么计划是什么? (So what is the plan?)

We can plan our way pretty well if we can think about the basic things that happens while validating:

如果我们可以考虑验证时发生的基本情况,则可以很好地计划我们的方法:

The above flowchart is a very abstract representation of our entire design. To shed more light onto the actual code, take a look at the following image:

上面的流程图非常抽象地表示了我们的整个设计。 为了使更多的信息更加真实,请看下面的图片:

足够了,让我们编写代码! (Enough is enough — let’s code!)

The following interface helps in maintaining the consistency across different validators we define.

以下接口有助于保持我们定义的不同验证器之间的一致性。

Now let us write some implementations for a few common validators.

现在让我们为一些常见的验证器编写一些实现。

Some validators may need few extra parameters. For example, FormatValidator requires a format parameter, and those parameters can be added as fields in the class.

一些验证器可能需要很少的额外参数。 例如, FormatValidator需要format参数,并且这些参数可以作为字段添加到类中。

There are number of ways to display an error. You might prefer to display it right below the control, or you might prefer to show it as a summary at the top of the form. To accommodate these different styles of showing errors, we define an interface for it to maintain consistency.

有多种显示错误的方法。 您可能希望将其显示在控件的正下方,或者可能希望将其作为摘要显示在表单的顶部。 为了适应这些不同的显示错误样式,我们定义了一个接口来保持一致性。

For the sake of simplicity, I have implemented a very basic error style which just adds and removes a label below the control being validated.

为了简单起见,我实现了一个非常基本的错误样式,该样式仅在要验证的控件下方添加和删除标签。

Now it is time for the Xamarin Behavior part, which glues together all the above code.

现在是Xamarin Behavior部分的时候了,该部分将上述所有代码粘合在一起。

_style: This field is initialised with our custom BasicErrorStyle implementation. This will help us show and remove the error whenever its needed.

_style:此字段是使用我们的自定义BasicErrorStyle实现初始化的。 这将帮助我们在需要时显示和删除错误。

_view: This is the control on which this validation is placed.

_view:这是放置验证的控件。

PropertyName: This is the property of the control which is to be validated against validation rules, let's say Text property of a Entry control or SelectedItem property of a picker control.

PropertyName:这是要根据验证规则进行验证的控件的属性,比方说Entry控件的Text属性或Picker控件的SelectedItem属性。

Validators: This is the list of validation rules against which the control property will be validated.

验证程序:这是将对照控件属性进行验证的验证规则的列表。

The Validate() method runs through all the validation rules and executes the Check method on the property value of the control. If all the validation rules pass, then the RemoveError method is called on _style. Otherwise the ShowError method is called on _style.

Validate()方法贯穿所有验证规则,并在控件的属性值上执行Check方法。 如果所有验证规则均通过,则在_style上调用RemoveError方法。 否则,将在_style上调用ShowError方法。

The remaining part of code just attaches and detaches the OnPropertyChanged, OnUnFocussed method to PropertyChanged and UnFocussed event of the control whenever this behavior is added to the xaml.

每当将此行为添加到xaml时,代码的其余部分仅将OnPropertyChanged,OnUnFocussed方法附加和分离到控件的 PropertyChanged和UnFocussed事件。

When these events are triggered, they call the Validate() method we defined earlier which in-turn adds or removes the error as needed.

触发这些事件后,它们将调用我们前面定义的Validate()方法,该方法又会根据需要添加或删除错误。

如何使用它 (How to use it)

Yes the wait is finally over! Now you can add these validations to your xaml by importing the necessary xaml namespaces.

是的,等待终于结束了! 现在,您可以通过导入必要的xaml名称空间将这些验证添加到您的xaml中。

If you run the app now, you should experience something like this:

如果您现在运行该应用程序,则应该会遇到以下情况:

验证整个表格 (Validating the entire form)

Now comes the next challenge: how we know whether the entire form is valid? That is, how do we know that all the controls in the form have valid data?

现在是下一个挑战:我们如何知道整个表格是否有效? 也就是说,我们如何知道表单中的所有控件都有有效数据?

To accomplish this, we create another behavior called ValidationGroupBehavior, in which we group the controls that are to be validated together to validate an entire form.

为此,我们创建了另一个称为ValidationGroupBehavior的行为在该行为中,我们将要验证的控件分组在一起以验证整个表单。

_validationBehaviors: this is a list of validation behaviors from various controls to be validated.

_validationBehaviors: 是来自要验证的各种控件的验证行为的列表。

IsValidProperty: this is a bindable property which you can access in the xaml to check whether the form is valid or not.

IsValidProperty:这是一个可绑定的属性,您可以在xaml中访问该属性以检查表单是否有效。

We expose two methods, namely Add() and Remove(), to help the controls add or remove themselves from a particular validation group.

我们公开了两个方法,即Add()Remove(),以帮助控件在特定的验证组中添加或删除自身。

We also expose a method, Update(), to help the controls for refreshing the validity of the form whenever their data changes. This method in turn runs all the validations in the _validationBehaviors and sets the value of the IsValid property accordingly.

我们还公开了Update()方法,以帮助控件在其数据更改时刷新表单的有效性。 该方法依次运行_validationBehaviors中的所有验证,并相应地设置IsValid属性的值。

重构我们的验证行为 (Refactoring our ValidationBehavior)

Let’s do a little refactoring to our ValidationBehavior class to accommodate the validation grouping of controls:

让我们对ValidationBehavior类进行一些重构,以容纳控件的验证分组:

We have added a property called Group to store the validation group to which the control belongs. The Group.Add() and Group.Remove() methods are called when this behavior is attached or detached, respectively, from a control. In turn, this adds or remove the control from a particular validation group. Whenever the control loses focus, it updates the validity of the group by calling the Group.Update() method.

我们添加了一个名为Group的属性来存储控件所属的验证组。 当此行为分别从控件中附加或分离时,将调用Group.Add()Group.Remove()方法。 反过来,这会将控件添加到特定的验证组中或从中删除。 每当控件失去焦点时,它将通过调用Group.Update()方法来更新组的有效性。

ValidationGroupBehavior的作用 (ValidationGroupBehavior in action)

Update the xaml file as shown below to see the awesomeness of the validation groups:

如下所示更新xaml文件,以查看验证组的强大功能:

The above code adds the ValidationGroupBehavior to the parent element of all controls, and then it adds its reference to the Group property of the Validator in the control. You can then use the IsValid property of the validation group to enable or disable a submit button. Fancy stuff, right?

上面的代码将ValidationGroupBehavior添加到所有控件的父元素,然后将其引用添加到控件中ValidatorGroup属性。 然后,您可以使用验证组的IsValid属性来启用或禁用提交按钮。 花哨的东西,对不对?

If you run the app now, you should see something like this:

如果您现在运行该应用程序,应该会看到类似以下内容:

异步验证器呢? (What about async validators?)

I can hear the question buzzing through your mind. One good thing about our design is that it can be extended very easily with little effort. This can be achieved by just declaring another interface as shown below:

我能听到你脑海中嗡嗡作响的问题。 关于我们的设计的一件好事是,可以很容易地轻松扩展它。 只需声明另一个接口即可实现,如下所示:

You can now create an implementation for an async validator, let's say AsyncUserExists, which returns a task that resolves to a boolean. Add a new property to ValidationBehavior called AsyncValidators and add async validators to that property. A little async and await addition to the validation process will solve our problem.

现在,您可以为异步验证器创建一个实现,比方说AsyncUserExists,它返回一个解析为布尔值的任务。 向ValidationBehavior添加一个名为AsyncValidators的新属性,然后向该属性添加异步验证器。 有点异步 并等待验证过程的补充将解决我们的问题。

我们终于完成了吗? (Are we done at last?)

We’ve covered quite a bit of info in a very simple way. But there are few nice-to-have features that you can try yourself:

我们已经以非常简单的方式介绍了很多信息。 但是,您可以尝试一些不错的功能:

  • Debounce for async validators

    为异步验证器进行反跳
  • Check if the control is dirty (user typed something) or not before showing an error

    在显示错误之前,请检查控件是否脏(用户键入了什么)

困惑? (Confused?)

If you are confused or have some gray areas, feel free to reach out to me in the comments. You can also refer to my demo app in GitHub which I have linked below.

如果您感到困惑或有一些灰色区域,请随时在评论中与我联系。 您还可以在下面链接的GitHub中引用我的演示应用程序。

ameerthehacker/XamarinFormValidationDemoXamarinFormValidationDemo - This is a demo app for my medium blog on xamarin form validationsgithub.com

ameerthehacker / XamarinFormValidationDemo XamarinFormValidationDemo-这是我的xamarin表单验证媒体博客的演示应用程序 github.com

TL; DR (TL;DR)

If you are lazy like me, or don't want to write a whole lot to get the above functionality, then you can wait until I develope a NuGet package for xamarin form validations using the above strategy. You are welcome to contribute to it, and I have linked to it below.

如果您像我一样懒惰,或者不想写很多书来获得上述功能,那么您可以等到我使用上述策略为xamarin表单验证开发NuGet程序包。 欢迎您为它做贡献,我在下面链接到它。

ameerthehacker/XamarinFormValidationXamarinFormValidation - Delcarative, flexible and highly configurable validations in Xamarin without a sweat :hearts:github.com

ameerthehacker / XamarinFormValidation XamarinFormValidation-Xamarin中的Delcarative,灵活和高度可配置的验证,不费吹灰之力:hearts: github.com

If you found this article helpful, give me some claps ?

如果您觉得这篇文章有帮助,请给我一些鼓掌?

翻译自: https://www.freecodecamp.org/news/declarative-xamarin-form-validation-c174d2a74618/

xamarin

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值