あれこれ
コントロールをValidation対象外にするには...
対応策1
* 対象外コントロールのプロパティ「CausesValidation : False」にする
# 例1であれば、再ゲーム用ボタンのプロパティ「CausesValidation : False」を指定すれば、検証対象外となる
対応策2
* 対象コントロールおよびValidationコントロールのプロパティ「ValidationGroup : 【任意の文字列(例「Ans」など)】」を指定する
# 例1であれば、Button(回答用ボタン)/RequiredFieldValidator/RangeValidatorのプロパティ「ValidationGroup : "Ans"」を指定すれば、再ゲーム用ボタンは検証対象外となる
例1
http://blogs.yahoo.co.jp/dk521123/25326361.html
条件付きの検証を行うには...
http://www.atmarkit.co.jp/fdotnet/dotnettips/237aspcondvali/aspcondvali.html
だと、PostBackが発生する。CustomValidatorと動的に作成したJSで実装する。
サンプル(デザイン)
* TextBox1が何もないが、TextBox2には値が入っている場合、エラーを表示させる場合の実装。
<asp:TextBox ID="TextBox1" runat="server" ValidationGroup="sampleError"></asp:TextBox>
-
<asp:TextBox ID="TextBox2" runat="server" ValidationGroup="sampleError"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox2" ErrorMessage="CustomValidator"
ValidationGroup="sampleError"></asp:CustomValidator>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button"
ValidationGroup="sampleError" />
サンプル(コードビハインド)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cs = Me.ClientScript
Dim script As StringBuilder = New StringBuilder()
script.AppendLine("<script language='javascript' type='text/javascript'>")
script.AppendLine("function custom_Validate(sender, e) {")
script.AppendLine(" var text1 = document.getElementById('TextBox1').value;")
script.AppendLine(" var text2 = document.getElementById('TextBox2').value;")
script.AppendLine(" if ((text1 == null || text1 == '') && (text2 != null || text2 != '')) {")
script.AppendLine(" e.IsValid = false;")
script.AppendLine(" } else {")
script.AppendLine(" e.IsValid = true;")
script.AppendLine(" }")
script.AppendLine("}")
script.AppendLine("</script>")
cs.RegisterClientScriptBlock( _
Me.GetType, "custom_Validate", script.ToString())
Me.CustomValidator1.ClientValidationFunction = "custom_Validate"
End Sub
Protected Sub CustomValidator1_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If String.IsNullOrEmpty(TextBox1.Text) AndAlso _
Not String.IsNullOrEmpty(TextBox2.Text) Then
args.IsValid = False
Else
args.IsValid = True
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Label1.Text = Me.TextBox1.Text & " ~ " & Me.TextBox2.Text
End Sub