Purescript Halogen手动触发表单外的输入验证

时间:2018-04-24 19:34:54

标签: purescript halogen

我有输入字段,我用required属性标记,但无法找到触发验证检查的方法(我不在表单内部工作,因此使用默认的提交按钮操作对我不起作用。)

快速追踪搜索显示核心html元素类型的许多有效性函数,但我不确定如何将这些应用于卤素。

是否有某种方法可以触发DOM效果来检查页面上所有必需的输入并获得结果?

这是一个示例组件,展示了我正在努力实现的目标

import Prelude

import Data.Maybe (Maybe(..))
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HE
import Halogen.HTML.Properties as HP

data Message = Void

type State =
  { textValue :: String
  , verified :: Boolean
  }

data Query a = ContinueClicked a | InputEntered String a

inputHtml :: State -> H.ComponentHTML Query
inputHtml state =
  HH.div [ HP.class_ $ H.ClassName "input-div" ]
         [ HH.label_ [ HH.text "This is a required field" ]
         , HH.input [ HP.type_ HP.InputText
                    , HE.onValueInput $ HE.input InputEntered
                    , HP.value state.textValue
                    , HP.required true
                    ]
         , HH.button [ HE.onClick $ HE.input_ ContinueClicked ]
                     [ HH.text "Continue"]
         ]

verifiedHtml :: H.ComponentHTML Query
verifiedHtml =
  HH.div_ [ HH.h3_ [ HH.text "Verified!" ] ]

render :: State -> H.ComponentHTML Query
render state = if state.verified then verifiedHtml else inputHtml state

eval :: forall m. Query ~> H.ComponentDSL State Query Message m
eval = case _ of
  InputEntered v next -> do
    H.modify $ (_ { textValue = v })
    pure next
  ContinueClicked next -> do
    let inputValid = false -- somehow use the required prop to determine if valid
    when inputValid $ H.modify $ (_ { verified = true })
    pure next

initialState :: State
initialState =
  { textValue : ""
  , verified : false
  }

component :: forall m. H.Component HH.HTML Query Unit Message m
component =
  H.component
    { initialState: const initialState
    , render
    , eval
    , receiver: const Nothing
    }

1 个答案:

答案 0 :(得分:2)

我不认为依赖HTML表单验证是检查卤素应用程序中输入的最有效方法。但我会假设你有理由并提出答案。

首先,如果我们想要处理DOM元素,我们需要一种方法来检索它们。这是document.getElementById

的purescript版本
getElementById
    :: forall a eff
     . (Foreign -> F a)
    -> String
    -> Eff (dom :: DOM | eff) (Maybe a)
getElementById reader elementId =
    DOM.window
        >>= DOM.document
        <#> DOM.htmlDocumentToNonElementParentNode
        >>= DOM.getElementById (wrap elementId)
        <#> (_ >>= runReader reader)

runReader :: forall a b. (Foreign -> F b) -> a -> Maybe b
runReader r =
    hush <<< runExcept <<< r <<< toForeign

(现在不要担心新的进口,最后还有一个完整的模块)

getElementById函数使用read*函数(可能来自DOM.HTML.Types)来确定您获取的元素的类型,以及元素ID作为字符串。

要使用此功能,我们需要为HH.input添加额外的属性:

HH.input [ HP.type_ HP.InputText
         , HE.onValueInput $ HE.input InputEntered
         , HP.value state.textValue
         , HP.required true
         , HP.id_ "myInput"  <-- edit
         ]

除此之外:具有Show实例的sum类型比在各处硬编码stringy id更安全。我会把那个留给你。

冷却。现在我们需要从您ContinueClicked函数的eval分支中调用它:

ContinueClicked next ->
    do maybeInput <- H.liftEff $
            getElementById DOM.readHTMLInputElement "myInput"
    ...

这为我们提供了Maybe HTMLInputElement。并且HTMLInputElement应该具有validity类型的ValidityState属性,其中包含我们之后的信息。

DOM.HTML.HTMLInputElement有一个validity函数,可以让我们访问该属性。然后我们需要做一些外来值操作来尝试获取我们想要的数据。为简单起见,让我们试着拔出valid字段:

isValid :: DOM.ValidityState -> Maybe Boolean
isValid =
    runReader (readProp "valid" >=> readBoolean)

有了这个小帮手,我们可以完成ContinueClicked分支:

ContinueClicked next ->
    do maybeInput <- H.liftEff $
            getElementById DOM.readHTMLInputElement "myInput"

       pure next <*
       case maybeInput of
            Just input ->
                do validityState <- H.liftEff $ DOM.validity input
                   when (fromMaybe false $ isValid validityState) $
                        H.modify (_ { verified = true })
            Nothing ->
                H.liftEff $ log "myInput not found"

然后把它们放在一起我们有......

module Main where

import Prelude

import Control.Monad.Aff (Aff)
import Control.Monad.Eff (Eff)
import Control.Monad.Eff.Console (CONSOLE, log)
import Control.Monad.Except (runExcept)

import Data.Either (hush)
import Data.Foreign (Foreign, F, toForeign, readBoolean)
import Data.Foreign.Index (readProp)
import Data.Maybe (Maybe(..), fromMaybe)
import Data.Newtype (wrap)

import DOM (DOM)
import DOM.HTML (window) as DOM
import DOM.HTML.HTMLInputElement (validity) as DOM
import DOM.HTML.Types
    (ValidityState, htmlDocumentToNonElementParentNode, readHTMLInputElement) as DOM
import DOM.HTML.Window (document) as DOM
import DOM.Node.NonElementParentNode (getElementById) as DOM

import Halogen as H
import Halogen.Aff as HA
import Halogen.HTML as HH
import Halogen.HTML.Events as HE
import Halogen.HTML.Properties as HP
import Halogen.VDom.Driver (runUI)

main :: Eff (HA.HalogenEffects (console :: CONSOLE)) Unit
main = HA.runHalogenAff do
    body <- HA.awaitBody
    runUI component unit body

type Message
    = Void

type Input
    = Unit

type State
    = { textValue    :: String
      , verified     :: Boolean
      }

data Query a
    = ContinueClicked a
    | InputEntered String a

component
    :: forall eff
     . H.Component HH.HTML Query Unit Message (Aff (console :: CONSOLE, dom :: DOM | eff))
component =
    H.component
        { initialState: const initialState
        , render
        , eval
        , receiver: const Nothing
        }

initialState :: State
initialState =
  { textValue : ""
  , verified : false
  }

render :: State -> H.ComponentHTML Query
render state =
    if state.verified then verifiedHtml else inputHtml
  where
    verifiedHtml =
        HH.div_ [ HH.h3_ [ HH.text "Verified!" ] ]

    inputHtml =
        HH.div
            [ HP.class_ $ H.ClassName "input-div" ]
            [ HH.label_ [ HH.text "This is a required field" ]
            , HH.input
                [ HP.type_ HP.InputText
                , HE.onValueInput $ HE.input InputEntered
                , HP.value state.textValue
                , HP.id_ "myInput"
                , HP.required true
                ]
            , HH.button
                [ HE.onClick $ HE.input_ ContinueClicked ]
                [ HH.text "Continue" ]
             ]

eval
    :: forall eff
     . Query
    ~> H.ComponentDSL State Query Message (Aff (console :: CONSOLE, dom :: DOM | eff))
eval = case _ of
    InputEntered v next ->
        do H.modify (_{ textValue = v })
           pure next

    ContinueClicked next ->
        do maybeInput <- H.liftEff $
                getElementById DOM.readHTMLInputElement "myInput"

           pure next <*
           case maybeInput of
                Just input ->
                    do validityState <- H.liftEff $ DOM.validity input
                       when (fromMaybe false $ isValid validityState) $
                            H.modify (_ { verified = true })
                Nothing ->
                    H.liftEff $ log "myInput not found"

getElementById
    :: forall a eff
     . (Foreign -> F a)
    -> String
    -> Eff (dom :: DOM | eff) (Maybe a)
getElementById reader elementId =
    DOM.window
        >>= DOM.document
        <#> DOM.htmlDocumentToNonElementParentNode
        >>= DOM.getElementById (wrap elementId)
        <#> (_ >>= runReader reader)

isValid :: DOM.ValidityState -> Maybe Boolean
isValid =
    runReader (readProp "valid" >=> readBoolean)

runReader :: forall a b. (Foreign -> F b) -> a -> Maybe b
runReader r =
    hush <<< runExcept <<< r <<< toForeign