takachaa / .net-Framework

0 stars 0 forks source link

【Webフォーム】カスタムバリデーション #20

Open takachaa opened 6 years ago

takachaa commented 6 years ago

カスタムバリデーションの基本

<form id="form1" runat="server">
        <p>
            <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server" Height="19px" ></asp:TextBox>
            <asp:customvalidator runat="server" errormessage="CustomValidator" ControlToValidate="TextBox1" OnServerValidate="CustomValidate1_ServerValidate"></asp:customvalidator>

         </p>
         <p>
            <asp:Label ID="Label2" runat="server" Text="Label2"></asp:Label>
            <asp:TextBox ID="TextBox2" runat="server" Height="19px"></asp:TextBox>
        </p>
        <p>
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />     
        </p>

    </form>

以下のようにコードビハインド側にカスタムバリデーションの実装を行う

protected void CustomValidate1_ServerValidate(object source, ServerValidateEventArgs args)
{
            var text = args.Value;
            if (text == TextBox2.Text)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
}