Skip to content

Asynchronous validation #14

@ngw

Description

@ngw

Hello, sorry for opening an issue but there's no other support/community link.
Apparently I can't perform async validations, for example through a Task. Example at hand, I'm in need to validate an email with a graphql query on the backend to ensure it's not present in the DB.

Some example code to check on the email can be:

checkEmailAddress : Maybe Email -> String -> Task String String
checkEmailAddress emailMaybe emailAddress =
  case emailMaybe of
    Just { email } ->
      Task.fail "Email is taken"
    Nothing ->
      Task.succeed emailAddress

isTaken : String -> Task String String
isTaken email =
  query email
    |> Graphql.Http.queryRequest "/graphql"
    |> Graphql.Http.toTask
    |> Task.mapError(\_ -> "GraphQL error")
    |> Task.andThen(\result -> (checkEmailAddress result.user email))

It actually doesn't return a Validator (obviously) and must run as a Cmd.
I'm really struggling to find a solution here, I want to shoow the Command once the field is Valid, this is some quite ugly and badly deisgned code to do that inside InputEmail

InputEmail e ->
  ( { model
      | email =
          model.email
          |> validate (OnChange e) emailValidation
    }
  , case validity (model.email |> validate (OnChange e) emailValidation) of
      Valid f -> Task.attempt ValidateEmailUniqueness (isTaken f)
      _ -> Cmd.none
  )

which has the problem that then I don't really have a way to build my own Field as Validator doesn't export Field(..) for example:

ValidateEmailUniqueness emailCheck ->
    ( { model
        | email = case emailCheck of
            Ok email -> Field email Valid
            Err err -> errorhandling
    }
  , Cmd.none)

(last snippet is made up)
Did you guys attempt to do anything like this and came up with something better than what I'm doing? Any suggestion?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions