验证跨越多个字段 [英] Validation spanning multiple fields

查看:129
本文介绍了验证跨越多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试应用表单,并且一直在想如何实现一个验证依赖于其他字段的字段的表单。例如一个注册表单,其中密码 confirm_password 字段,我想验证密码== confirm_password



在表单运行后,我可以在处理程序中完成,但这意味着会丢失错误消息。



编辑:忘了提及,我主要使用Yesods应用表单,但它们似乎与消化函数相当接近 p>

解决方案

您使用的是什么类型的表单系统?您可以使用消化函数轻松做到这一点,以下是我的一个注册表格示例:

  registrationForm = 
注册
< $> username。:text Nothing
< *> password。:passwordConfirmer
where passwordConfirmer =
validate fst'$(,)< $> (p1。:text nothing)
* (p2。:text Nothing)
fst'(p1,p2)| p1 == p2 =成功p1
|否则=错误密码必须匹配

在这里您可以看到我为密码字段通过使用我的 passwordConfirmer 表单字段。这个字段使用2个文本字段并将它们放入一个元组中,但验证后只需要 fst 元素(尽管它可能需要 snd $ b $ My 注册类型是: p>

  data注册=注册
{regUserName :: Text
,regPassword :: Text
}


I'm trying to grok applicative forms, and I've been wondering how to implement a form that validates fields that depend on other fields. For example a registration form which has password and confirm_password fields and I'd like to validate that password == confirm_password.

I could be done after the form has ran, in the handler, but that would mean losing error messages.

Edit: Forgot to mention, I'm mainly using Yesods applicative forms, but they seem to be quite close to digestive-functors

解决方案

What type of form system are you using? You can easily do this with digestive-functors, here's an example of one of my registration forms:

registrationForm =
    Registration
      <$> "username" .: text Nothing
      <*> "password" .: passwordConfirmer
  where passwordConfirmer =
          validate fst' $ (,) <$> ("p1" .: text Nothing)
                              <*> ("p2" .: text Nothing)
        fst' (p1, p2) | p1 == p2  = Success p1
                      | otherwise = Error "Passwords must match"

Here you can see I generate a value for my 'password' field by using my passwordConfirmer form field. This field uses 2 text fields and puts them into a tuple, but after validation it just takes the fst element (though it could take snd, we've guaranteed they are equal!).

My Registration type is:

data Registration = Registration
    { regUserName :: Text
    , regPassword :: Text
    }

这篇关于验证跨越多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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