回答編集履歴
3
誤字の修正
answer
CHANGED
@@ -28,11 +28,11 @@
|
|
28
28
|
}
|
29
29
|
if (string.IsNullOrEmpty(this.B))
|
30
30
|
{
|
31
|
-
yield return new ValidationResult("Bは入力が必須です。", new string[] { "
|
31
|
+
yield return new ValidationResult("Bは入力が必須です。", new string[] { "B" });
|
32
32
|
}
|
33
33
|
if (string.IsNullOrEmpty(this.C))
|
34
34
|
{
|
35
|
-
yield return new ValidationResult("Cは入力が必須です。", new string[] { "
|
35
|
+
yield return new ValidationResult("Cは入力が必須です。", new string[] { "C" });
|
36
36
|
}
|
37
37
|
}
|
38
38
|
}
|
2
質問者の追記を拝見し修正
answer
CHANGED
@@ -2,6 +2,11 @@
|
|
2
2
|
つまりアノテーション1行では表現できないはずです。
|
3
3
|
従って、モデルにIValidatableObjectインターフェイスを実装してValidateメソッドで行うのが普通ではないでしょうか。
|
4
4
|
|
5
|
+
質問者様の追記を見て下記仕様と想定し、ソースコードを記載します。
|
6
|
+
- FLGのチェックボックスがONのときのみテキストボックスA、B、Cの必須チェックを行う
|
7
|
+
- チェックボックスがOFFの時はABCは非活性
|
8
|
+
- Dだけは常に必須チェックを行う
|
9
|
+
|
5
10
|
```C#
|
6
11
|
[Serializable]
|
7
12
|
public class TestModel : IValidatableObject
|
@@ -10,6 +15,7 @@
|
|
10
15
|
public string A { get; set; }
|
11
16
|
public string B { get; set; }
|
12
17
|
public string C { get; set; }
|
18
|
+
[Required]
|
13
19
|
public string D { get; set; }
|
14
20
|
|
15
21
|
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
@@ -28,10 +34,6 @@
|
|
28
34
|
{
|
29
35
|
yield return new ValidationResult("Cは入力が必須です。", new string[] { "B" });
|
30
36
|
}
|
31
|
-
if (string.IsNullOrEmpty(this.D))
|
32
|
-
{
|
33
|
-
yield return new ValidationResult("Dは入力が必須です。", new string[] { "D" });
|
34
|
-
}
|
35
37
|
}
|
36
38
|
}
|
37
39
|
}
|
1
ソースコードの追記
answer
CHANGED
@@ -1,3 +1,38 @@
|
|
1
1
|
条件付きの必須ということは、その条件のロジックを実装する必要があります。
|
2
2
|
つまりアノテーション1行では表現できないはずです。
|
3
|
-
従って、モデルにIValidatableObjectインターフェイスを実装してValidateメソッドで行うのが普通ではないでしょうか。
|
3
|
+
従って、モデルにIValidatableObjectインターフェイスを実装してValidateメソッドで行うのが普通ではないでしょうか。
|
4
|
+
|
5
|
+
```C#
|
6
|
+
[Serializable]
|
7
|
+
public class TestModel : IValidatableObject
|
8
|
+
{
|
9
|
+
public string Flg { get; set; }
|
10
|
+
public string A { get; set; }
|
11
|
+
public string B { get; set; }
|
12
|
+
public string C { get; set; }
|
13
|
+
public string D { get; set; }
|
14
|
+
|
15
|
+
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
16
|
+
{
|
17
|
+
if (this.Flg == "1")
|
18
|
+
{
|
19
|
+
if (string.IsNullOrEmpty(this.A))
|
20
|
+
{
|
21
|
+
yield return new ValidationResult("Aは入力が必須です。", new string[] { "A" });
|
22
|
+
}
|
23
|
+
if (string.IsNullOrEmpty(this.B))
|
24
|
+
{
|
25
|
+
yield return new ValidationResult("Bは入力が必須です。", new string[] { "C" });
|
26
|
+
}
|
27
|
+
if (string.IsNullOrEmpty(this.C))
|
28
|
+
{
|
29
|
+
yield return new ValidationResult("Cは入力が必須です。", new string[] { "B" });
|
30
|
+
}
|
31
|
+
if (string.IsNullOrEmpty(this.D))
|
32
|
+
{
|
33
|
+
yield return new ValidationResult("Dは入力が必須です。", new string[] { "D" });
|
34
|
+
}
|
35
|
+
}
|
36
|
+
}
|
37
|
+
}
|
38
|
+
```
|