DEV Community

Vivek Raj
Vivek Raj

Posted on

Validator Function in Haskell

{-# LANGUAGE TypeApplications #-}

module Main where

import Data.Char (isAlphaNum, isSpace)

maxLength :: String -> Maybe String
maxLength "" = Nothing
maxLength xs =
  case (length xs > 20) of
    True -> Nothing
    False -> Just xs

allAlpha :: String -> Maybe String
allAlpha "" = Nothing
allAlpha xs =
  case (all isAlphaNum xs) of
    False -> Nothing
    True -> Just xs

stripSpace :: String -> Maybe String
stripSpace "" = Nothing
stripSpace (x : xs) =
  case (isSpace x) of
    True -> stripSpace xs
    False -> Just (x : xs)

validatePassword :: String -> Maybe String
validatePassword password =
  stripSpace password >>= allAlpha >>= maxLength

main :: IO ()
main = do
  putStrLn "Please enter a password"
  password <- getLine
  print (validatePassword password)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
armousness profile image
Sean Williams

If you're so inclined, you can also write validatePassword as,

validatePassword :: String -> Maybe String
validatePassword p = foldl (>>=) (Just p) [stripSpace, maxLength, allAlpha]
Enter fullscreen mode Exit fullscreen mode

Main advantage being, you can separate out your list of validators and, for example, reuse them elsewhere...

validators :: [String -> Maybe String]
validators = [stripSpace, maxLength, allAlpha]

validatePassword :: String -> Maybe String
validatePassword p = foldl (>>=) (Just p) validators
Enter fullscreen mode Exit fullscreen mode