1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

test20241031

Posted at
  1. Data Annotations ライブラリをインポート

まず、System.ComponentModel.DataAnnotations 名前空間をインポートします。

Imports System.ComponentModel.DataAnnotations
  1. モデルクラスの定義

次に、モデルクラスにアノテーションを使ってバリデーションルールを定義します。

Public Class User
    <Required(ErrorMessage := "Name is required")>
    <StringLength(50, ErrorMessage := "Name cannot exceed 50 characters")>
    Public Property Name As String

    <Range(18, 99, ErrorMessage := "Age must be between 18 and 99")>
    Public Property Age As Integer

    <EmailAddress(ErrorMessage := "Invalid email format")>
    Public Property Email As String
End Class

この例では、Name プロパティに必須制約と文字数制限を、Age プロパティに範囲制約を、Email プロパティにメール形式の制約を追加しています。

  1. バリデーションの実行

次に、Validator クラスを使ってバリデーションを実行し、エラーメッセージを取得します。

Public Function ValidateModel(model As Object) As List(Of ValidationResult)
    Dim results As New List(Of ValidationResult)
    Dim context As New ValidationContext(model, Nothing, Nothing)
    
    If Not Validator.TryValidateObject(model, context, results, True) Then
        ' エラーメッセージを出力
        For Each result As ValidationResult In results
            Console.WriteLine(result.ErrorMessage)
        Next
    End If

    Return results
End Function
  1. 使用例

モデルインスタンスを作成し、ValidateModel メソッドでバリデーションを実行します。

Sub Main()
    Dim user As New User() With {
        .Name = "", ' 無効な入力
        .Age = 17, ' 無効な入力
        .Email = "invalid-email" ' 無効な入力
    }

    Dim validationResults = ValidateModel(user)
    If validationResults.Count = 0 Then
        Console.WriteLine("Validation passed")
    Else
        Console.WriteLine("Validation failed")
    End If
End Sub
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?