Blog Content

    티스토리 뷰

    34.C# ASP.NET - CustomValidator [ 유효성검사컨트롤 ]

    반응형
    CustomValidator :

    FrmCustomValidator.aspx

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head runat="server">

        <title></title>

        <script> // 클라이언트 레벨이라 서버에 부하를 줄여줌

            function ClientValidate(sender, args) {

                if (args.Value.length < 3 || args.Value.length > 12) {

                    args.IsValid = false;

                }

               

                else {

                    args.IsValid = true;

                }

            }

        </script>

    </head>

     

    <body>

        <form id="form1" runat="server">

        <div>

            아이디 :

            <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox><br />

            <asp:Button ID="btnOK" runat="server" Text="확인" />

           

            <asp:CustomValidator ID="CustomerValidator1" runat="server"

                ControlToValidate="txtUserID"

                ClientValidationFunction="ClientValidate"

                ErrorMessage="아이디는 3 이상 12 이하"

                onservervalidate="valCustomer_ServerValidate"></asp:CustomValidator>

        </div>

        </form>

    </body>

    </html>


    FrmCustomValidator.aspx.cs

    protected void valCustomer_ServerValidate(object source, ServerValidateEventArgs args)

    {

        // 서버 컨트롤로 있는 최대한 자바스크립트로 처리

        // 서버의 부하를 줄여주기 위해서

        string userID = args.Value; // 지정된 텍스트박스의 값을 받아서

        if (userID.Length < 3 || userID.Length > 12)

        {

            args.IsValid = false; // 에러

        }

     

        else

        {

            args.IsValid = true; // 유효성 통과

        }

    }


    결과화면

    [그림34-1]



    FrmCustomValidator.htm

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

        <title></title>

        <script type="text/javascript">

            function CheckNum() {

                var obj = document.getElementById("txtEven");

                if (obj.value % 2 == 0) {

                    alert("통과");

                }

                else {

                    alert("에러");

                }

            }

        </script>

    </head>

    <body>

     

        짝수만 입력 : <input type="text" id="txtEven" /><br />

        <input type="button" value="짝수만 입력" onclick="CheckNum();" />

     

    </body>

    </html>


    결과화면

    [그림34-2]



    반응형

    Comments