DEV Community

Vivek Raj
Vivek Raj

Posted on

2 2

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay