WPF DataValidation in F#

This time I want to do some data validation.

data validation

So I’m showing a value from the config with the possibility to update it when it represents a list of integers.

let splitCpties str =
    if String.IsNullOrWhiteSpace str then [||]
    else str.Split(" ;,-".ToCharArray())
let tryParseWith tryParseFunc = tryParseFunc >> function
    | true, v    -> Some v
    | false, _   -> None
let parseInt    = tryParseWith Int32.TryParse
let setCpties str = Array.choose parseInt > Option.isNone) 
        self.ExcludedCpties <- self.ExcludedCpties + " (" + e.Message + ")"

and

member x.ExcludedCpties with get() = excludedCpties.Value and set value = excludedCpties.Value <- value 
member x.SaveExCpties = self.Factory.CommandSyncChecked(saveExCpties, (fun () -> invalidCpties x.ExcludedCpties |> not), [  ])

So the save button is disabled if the validation fails, but I want also to prevent from processing the payments in that case.

data validation 2

 So… I invent my own way of doing it.

let redError = self.Factory.Backing(, "") 
let showRedError error =
    self.RedError <- error
    error
let isValid () = String.IsNullOrWhiteSpace redError.Value 

and

interface IDataErrorInfo with
    member this.Error = failwith "error not implemented"
    member this.Item 
           with get propertyName = 
            match propertyName, invalidCpties excludedCpties.Value with 
            | "ExcludedCpties", true -> 
                showRedError "each cpty must be an integer value!"
            | "ExcludedCpties", false ->
                let intCpties = setCpties excludedCpties.Value
                let check = Array.groupBy id intCpties
                match Array.tryFind (fun (i, c) -> c |> Array.length > 1 ) check with
                | Some (x,y)  -> showRedError ( x.ToString() + " is duplicated" )
                | None -> showRedError null
            | _ , _ ->  showRedError null

and then I can use the red error in a command or a textblock like the following

<TextBlock Foreground="Red" Text="{Binding RedError}" ...  />
member x.LoadInvoicesCmd  = self.Factory.CommandAsyncChecked( loadInvoices, isValid, [ <@ self.RedError @> ]) 

One thought on “WPF DataValidation in F#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s