2012-08-24 46 views
7

我正在嘗試groh應用程序的形式,我一直想知道如何實現一個窗體驗證依賴於其他字段的字段。例如一個登記表,其中passwordconfirm_password字段,我想驗證password == confirm_password驗證跨越多個字段

我可以在表單運行後在處理程序中完成,但這意味着會丟失錯誤消息。

編輯:忘了提,我主要是利用Yesods合用的形式,但他們似乎是相當接近的消化,仿函數

您正在使用什麼類型的表單系統

回答

7

?您可以輕鬆地digestive-functors做到這一點,這裏是我的登記表中的一個例子:

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" 

在這裏你可以看到我爲我的「密碼」字段中的值用我的passwordConfirmer表單字段。該字段使用2個文本字段並將它們放入一個元組中,但驗證後只需要fst元素(儘管可能需要snd,我們保證它們是相等的!)。

Registration類型:

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

我使用yesods合用的形式,但這是很好的答案太 – Masse