본문 바로가기

js/jQuery

[validate] 예제





js include


<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery.validate.js"></script>



html


<form id="loginForm">     <div class="form-group form-horizontal form-inline">     <label class="control-label col-lg-2" for="LoginId">아이디</label> <input type="text" class="form-control" id="LoginId" name="LoginId" placeholder="아이디">     </div> <div class="form-group form-horizontal form-inline">     <label class="control-label col-lg-2" for="Password">비밀번호</label>     <input type="password" class="form-control" id="Password" name="Password" placeholder="비밀번호">  </div> <div class="btn-group-lg">     <button type="button" class="btn btn-lg btn-success col-lg-offset-2" id="btnLogin" onclick="$(this.form).submit()">로그인</button>    </div> </form>


js code


    <script type="text/javascript">
    $(function () {
        $('#loginForm').validate({
            debug: false,
            onfocusout: false,
            rules: {
                LoginId: {
                    required: true,
                    rangelength: [2, 20]
                },
                Password: {
                    required: true,
                    rangelength: [2, 20]
                }
            }, messages: {
                LoginId: {
                    required: '아이디를 입력하세요.',
                    rangelength: $.validator.format('{0}자 내로 입력하세요.')
                },
                Password: {
                    required: '비밀번호를 입력하세요.',
                    rangelength: $.validator.format('{0}자 내로 입력하세요.')
                }
            }, errorPlacement: function (error, element) {
                // do nothing
            }, invalidHandler: function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    alert(validator.errorList[0].message);
                    validator.errorList[0].element.focus();
                }
            }, submitHandler: function (form) {

                var dataCollection = $(form).serialize();

                $.post("http://localhost:7314/Proc/HomeLogin",
                    dataCollection,
                    function (data, textStatus, jqXHR) {
                        console.log(data.data);
                        var result = $.parseJSON(data.data);

                        if (result.Message == "EXISTS") {
                            alert("정상적으로 로그인 되었습니다.");
                        } else {
                            alert(result.Message);
                        }
                    }
                );
            }
        });
    });

    </script>