설 연수
하하호홓
설 연수
전체 방문자
오늘
어제
  • 분류 전체보기 (231)
    • Back-End (2)
      • Java (20)
      • JSP (13)
      • Spring (18)
      • Kotlin (0)
      • node.js (0)
    • Front-End (68)
      • JavaScript (19)
      • jQuery (39)
      • Angular (4)
      • HTML (5)
    • Dev-Ops (12)
      • Linux, Cloud (5)
      • docker, k8s (5)
      • ElasticSeach (2)
    • Other (33)
      • OOP (3)
      • 알고리즘 (2)
      • DB (12)
      • Git (1)
      • Swift (4)
    • Backup (65)

블로그 메뉴

    공지사항

    인기 글

    태그

    • angular2
    • angular 콜백
    • RESTful
    • 패스트캠퍼스
    • INVALID
    • angular4
    • Redis
    • Angular
    • page not found
    • 404 error
    • jquery invalid
    • Kafka
    • CORS
    • docker
    • MYSQL
    • flex
    • jOOQ
    • angular callback
    • mongodb
    • 크로스도메인

    최근 댓글

    최근 글

    티스토리

    hELLO · Designed By 정상우.
    설 연수

    하하호홓

    Front-End/jQuery

    HTML5 input required, $("input:invalid") 활용

    2018. 2. 13. 16:22

    input required : 필수값여부

    document.querySelectorAll('input:valid') : valid input 찾기

    document.querySelectorAll('input:invalid') : invalid input 찾기

    document.forms[0].checkValidity() : 폼 내 dom들 validation체크

    $("input:invalid") : jquery로 invalid input 찾기(jquery invalid extend필수)


    html5 기능은 ie9부턴가 지원되니까, ie9이상환경 프로젝트나 모바일/태블릿프로젝트에서 활용

    WEB TEST : https://jsfiddle.net/ab5saeav/



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            // jquery invalid확장.
            jQuery.extend(jQuery.expr[':'], {
                valid : function(elem, index, match){
                    var valids = document.querySelectorAll(':valid'),
                        result = false,
                        len = valids.length;
     
                    if (len) {
                        for (var i=0; i<len; i++) {
                            if (elem === valids[i]) {
                                result = true;
                                break;
                            }
                        }
                    }
                    return result;
                },
                invalid : function(elem, index, match){
                    var invalids = document.querySelectorAll(':invalid'),
                        result = false,
                        len = invalids.length;
     
                    if (len) {
                        for (var i=0; i<len; i++) {
                            if (elem === invalids[i]) {
                                result = true;
                                break;
                            }
                        }
                    }
                    return result;
                }
            });
     
            function validTest(){
                console.log("valid input개수 : " + document.querySelectorAll('input:valid, select:valid').length);
            }
     
            function invalidTest(){
                console.log("invalid input개수 : " + document.querySelectorAll('input:invalid, select:invalid').length);
            }
     
            function checkValidity1(){
                console.log("validate 체크결과 : " + document.forms[0].checkValidity());
            }
     
            function checkValidity2(){
                console.log("validate 체크결과 : " + document.testForm.checkValidity());
            }
     
            function jqueryInvalid(){
                console.log($("input:invalid, select:invalid"))
                console.log('$("input:invalid, select:invalid").length :' + $("input:invalid, select:invalid").length);
            }
     
            function jqueryValid(){
                console.log($("input:valid, select:valid"))
                console.log('$("input:valid, select:valid").length :' + $("input:valid, select:valid").length);
            }
     
            function jqueryInvalid2(){
                if( document.forms[0].checkValidity() ){
                    alert("validation 통과");
                } else {
                    // 1. jquery
                    //alert( $("input:invalid, select:invalid").eq(0).attr("placeholder") );
     
                    // 2. javascript
                    alert( document.querySelectorAll('input:invalid')[0].placeholder );
                }
            }
        </script>
    </head>
    <body>
        <form action="#" method = "get" name="testForm">
            <label for="userName">(필수)이름: </label>
              <input id="userName" name="userName" type="text" placeholder="이름을 입력해주세요" required/>
              <br/>
     
            <label for="age">(필수)나이: </label>
              <input id="age" name="age" type="number" min="1" max="5" placeholder="나이을 입력해주세요" required/>
              <br/>
     
              <label for= "email"> Email: </label>
              <input id= "email" name="email" type="email" placeholder="이메일을 입력해주세요" />
              <br/>
     
              <label for="phone">(필수)Phone: </label>
              <input id="phone" name="phone" type="phone" placeholder="휴대폰번호를 입력해주세요" required/>
            <br/>
              <select name="selectTest" required>
                  <option value="">value값 없음</option>
                  <option value="1">value값 있음</option>
              </select>
              <br/>
              <button type="submit"> Submit Form </button>
              <br/><br/><br/><br/>
              <br/>
              ※ html5 기능은 ie9부턴가 지원되니까, ie9이상환경 프로젝트나 모바일/태블릿프로젝트에서 활용가능<br/>
            required : 필수여부<br/>
              <br/><br/>
              <button type="button" onclick="validTest();"> document.querySelectorAll('input:valid') </button><br/>
              <button type="button" onclick="invalidTest();"> document.querySelectorAll('input:invalid') </button><br/>
              <br/>
              value값 null여부 및 그외조건(min~max사이 등 설정해놓은조건....)에 일치하는지 체크<br/>
              input type email일경우, email형식에 일치하도록 입력안하면 false임.<br/>
              <button type="button" onclick="checkValidity1();"> document.forms[0].checkValidity() </button><br/>
              <button type="button" onclick="checkValidity2();"> document.testForm.checkValidity() </button><br/>
              <br/><br/>
              jquery Selector invalid 확장.
              <br/>
              <button type="button" onclick="jqueryInvalid();"> $("input:invalid, select:invalid") </button><br/>
              <button type="button" onclick="jqueryValid();"> $("input:valid, select:valid") </button><br/>
              <br/><br/>
              <button type="button" onclick="jqueryInvalid2();"> jquery/javascript validation예제  </button><br/>
        </form>
    </body>
     
     
    Colored by Color Scripter
    cs


    저작자표시 (새창열림)

    'Front-End > jQuery' 카테고리의 다른 글

    Template literals  (0) 2018.04.09
    jquery promise, Deferred 테스트  (0) 2018.01.30
    jQuery Selectable(UI) 컨트롤안누르고도 다중선택하기  (0) 2014.05.07
    jquery 강제 엔터처리  (0) 2014.01.20
    jqGrid Pager(Navigator) 옵션주기  (0) 2012.11.01
      'Front-End/jQuery' 카테고리의 다른 글
      • Template literals
      • jquery promise, Deferred 테스트
      • jQuery Selectable(UI) 컨트롤안누르고도 다중선택하기
      • jquery 강제 엔터처리
      설 연수
      설 연수

      티스토리툴바