Created
February 26, 2011 16:41
-
-
Save masaedw/845375 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| open System | |
| #r "System.ComponentModel.DataAnnotations" | |
| open System.ComponentModel.DataAnnotations | |
| open System.Collections.Generic | |
| type Person() = | |
| let mutable name = "" | |
| let mutable phone = "" | |
| let mutable age = 0 | |
| // 名前は必須 | |
| [<Required>] | |
| member p.Name | |
| with get() = name | |
| and set(v) = name <- v | |
| // 電話番号も必須で、番号のフォーマットが規定されている | |
| [<Required>] | |
| [<RegularExpression(@"^[0-9]{3}-[0-9]{4}-[0-9]{4}$")>] | |
| member p.Phone | |
| with get() = phone | |
| and set(v) = phone <- v | |
| // 年齢は 3-100 歳でなければならない | |
| [<Range(3,100)>] | |
| member p.Age | |
| with get() = age | |
| and set(v) = age <- v | |
| // バリデーション結果を表示する | |
| let printValidationResults (results:ValidationResult seq) = | |
| let message_of (r:ValidationResult) = | |
| String.Join(", ", r.MemberNames) + ": " + r.ErrorMessage | |
| results | |
| |> Seq.map message_of | |
| |> (fun x -> String.Join("\n", x)) | |
| |> printfn "%s" | |
| // バリデートして結果を表示する | |
| let validate p = | |
| let c = new ValidationContext(p, null, null) | |
| let r = new List<ValidationResult>() | |
| if Validator.TryValidateObject(p, c, r, true) | |
| then | |
| printfn "検証エラー無し\n" | |
| else | |
| Seq.cast r | |
| |> printValidationResults | |
| let main() = | |
| let p = new Person() | |
| validate p | |
| (* | |
| Name: Name フィールドが必要です。 | |
| Phone: Phone フィールドが必要です。 | |
| Age: フィールド Age は 3 から 100 までの範囲で指定してください。 | |
| *) | |
| p.Name <- "taro" | |
| p.Age <- 33 | |
| p.Phone <- "123-4567-8901" | |
| validate p | |
| (* | |
| 検証エラー無し | |
| *) | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment