Phoenix框架-自定义变更集验证 [英] Phoenix framework - Custom changeset validations

查看:55
本文介绍了Phoenix框架-自定义变更集验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的对凤凰和长生不老药很陌生,所以如果这些看起来很简单,我会道歉。在考虑将其发布到这里之前,我已经搜索了堆栈溢出和博客。

I'm really new to phoenix and elixir, so my apologies if these seem like simple questions. I've searched stack overflow and blogs before I thought about posting it here.

我在模型中有2个字段,字段A:整数,字段B:整数。在使用变更集进行验证时,我想创建一个自定义验证,以在创建新项目时检查字段A是否大于字段b,如果是,则刷新一条错误消息并将其带回到:new路由。抱歉,如果我使用的术语不正确。

I've got 2 fields in a model, field A : integer and field B : integer. When doing my validations with my changeset I want to create a custom validation that checks if field A is more than field b when creating a new item, and if so then flash a error message and bring them back to the :new route. Sorry if I'm not using the right terminologies.

所以我想这现在成为一个由两部分组成的问题。首先,我是否应该通过创建自定义验证在模型中执行此操作,还是应该在控制器中执行此操作?其次,用phoenix写这个最简单的方法是什么?

So I guess this now becomes a 2 part question. First, should I even be doing this in my model by creating a custom validation or should this be in the controller? And second, what is the simplest way to write this in phoenix?

再次感谢。

推荐答案

我必须做这件事,这花了我一些时间来解决。我结束了为变更集编写自定义验证器。

I had to do this exact thing and it took me a bit of time to figure it out. I ended writing a custom validator for the changeset.

def changeset(model, params \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
  |> validate_a_less_eq_b
end

defp validate_a_less_eq_b(changeset) do
  a = get_field(changeset, :a)
  b = get_field(changeset, :b)

  validate_a_less_eq_b(changeset, a, b)
end
defp validate_a_less_eq_b(changeset, a, b) when a > b do
  add_error(changeset, :max, "'A' cannot be more than 'B'")
end
defp validate_a_less_eq_b(changeset, _, _), do: changeset

当然,您希望使用常规验证器来确保a和b是有效数字。

You would, of course, want to use regular validators to ensure that a and b are valid numbers.

这篇关于Phoenix框架-自定义变更集验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆