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

xamarin_如何实现声明性Xamarin表单验证相关推荐

  1. jsf表单验证_JSF验证示例教程–验证器标签,定制验证器

    jsf表单验证 JSF validation model defines a set of standard classes for validating the UI components. The ...

  2. JavaScript常用表单验证

    JavaScript常用表单验证 目录: 1:js 字符串长度限制.判断字符长度 .js限制输入.限制不能输入.textarea 长度限制 2.:js判断汉字.判断是否汉字 .只能输入汉字 3:js判 ...

  3. Angular 表单验证

    模板驱动验证 使用模板驱动验证需要依赖于原生的HTML表单验证器 Angular 会用指令来匹配具有验证功能的这些属性. 原生的HTMl验证器主要分两种 通过语义类型来进行定义 通过验证相关的属性来进 ...

  4. Angular响应式表单及表单验证

    1. 什么是响应式表单? 响应式表单提供了一种模型驱动的方式来处理表单输入,其中的值会随时间而变化. 响应式表单使用显示的,不可变的方式,管理表单在特定时间点上的状态.对表单状态的每一次变更都会返回一 ...

  5. AngularJS表单验证

    表单 网页中用户于服务端交互数据的表单控件有input.select.textarea,而表单是将为了达到一个目的(登录.注册等)各种控件整合到一起的一个集合. 表单和其中的表单控件提供了验证服务,可 ...

  6. JavaScript - JavaScript通用表单验证函数(实例)

    Check.js    JS函数文件 /* *--------------- 客户端表单通用验证CheckForm(oForm) ----------------- * 功能:通用验证所有的表单元素. ...

  7. 学习js,尝试写一个表单验证框架(1)-规划

    斗胆放到首页来,如果不合适的话就删了吧,谢谢 其实这个框架也已经写了一点了,但是越写越乱越没把握,最终决定写成博客的形式,强迫自己慢下步调,一点点仔细地规划,设计,思考,期间也一定会遇到不少问题,还请 ...

  8. JavaScript 笔记(2) -- 类型转换 正则表达 变量提升 表单验证

    目录:  typeof, null, undefined, valueOf() 类型转换 正则表达式 错误: try, catch, throw 调试工具 变量提升 strict 严格模式 使用误区 ...

  9. php ci提交表单验证,ci表单验证代码

    概述 这是只考虑php对表单数据的接收处理.至于js部分以前会结合validate来讲解下 在解释 CodeIgniter 的数据验证处理之前,让我们先描述一下一般的情况: 一个表单显示了. 你填写并 ...

最新文章

  1. EOS安全漏洞再发,BCH将如何兼顾智能合约效率与安全?
  2. laravel 安装配置前准备
  3. 20170728xlVBA改转置一例
  4. 使用SPEncode.HtmlEncodePreserverSpace保存输入
  5. react动态改变选中不选中_当使用react hooks选中任何复选框时,如何使启用按钮起作用?...
  6. 算法 - KMP算法(字符串匹配)
  7. STM32F4 串口DMA
  8. 第二章:变量和运算符
  9. 自定义filter中配置不被过滤的资源
  10. 写在使用 Linux 工作一年后
  11. 计算机调试致sa登录失败,无法打开登录 'xxxx' 中请求的数据库。登录失败。用户 'sa' 登录失败。解决思路...
  12. 开放 接口 饿了么_饿了么口碑启动生态赋能计划 将在210城开放智慧餐厅业务合作窗口...
  13. Axure中引入Echarts图表并制作元件库
  14. python木马程序设计_基于HTTP的Python特洛伊木马程序,用于远程系统取证和特权转移
  15. 自定义TimePicker样式,修改时分、分割线分隔冒号的字体、颜色高度等属性
  16. iOS app url scheme跳转到淘宝商品详情页 唤醒app
  17. Linux指令整理(从入门到高级)+Shell语法
  18. 02-SQL语句给表起别名SQL中的表连接
  19. 树莓派4B安装官方64位桌面系统
  20. Uni-app开发微信小程序使用本地图片做背景图

热门文章

  1. 查看未提交事务或sleep session最后执行的sql语句
  2. mysql使用全备文件恢复单个库或者单个表
  3. CSS浏览器兼容性与解决方法
  4. SequoiaDB扩容介绍与最佳实践
  5. linux下last与lastb命令详解
  6. [大数据行业应用发展前景分析] 阿里潘永花报告:大数据产业将成为新的煤和石油介绍...
  7. XBMC不能看搜狐电视剧
  8. IPSEC ×××需要解决的路由问题及影响IPSEC ×××的网络问题
  9. [Linux] 安装samba
  10. 我是如何带领团队开发项目的