JavaScript / 사업자등록번호, 전화번호 유효성 검사하는 방법

사업자등록번호 유효성 검사

  • 사업자등록번호를 입력하고 전송할 폼을 만들고, 버튼 클릭 시 checkBrn() 함수를 호출한다.
<input type="text" name="brn" id="brn">
<input type="button" value="Check" onclick="checkBrn();">
  • 메시지를 출력할 공간을 만든다.
<p id="checkBrnMessage"></p>
  • 입력한 값을 변수 brn에 담는다.
var brn = document.getElementById( "brn" ).value;
  • 정규표현식 /^[0-9]{3}-[0-9]{2}-[0-9]{5}$/를 이용하여 유효성 검사를 한다.
  • 000-00-00000 형식이 맞으면 OK, 그렇지 않으면 NOT OK를 출력한다.
if ( /^[0-9]{3}-[0-9]{2}-[0-9]{5}$/.test( brn ) ) {
  document.getElementById( "checkBrnMessage" ).innerText = "OK";
} else {
  document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
}

정규표현식을 반복적으로 사용한다면, 아래처럼 변수에 담아도 된다.

var brnRe = /^[0-9]{3}-[0-9]{2}-[0-9]{5}$/;
if ( brnRe.test( brn ) ) {
  document.getElementById( "checkBrnMessage" ).innerText = "OK";
} else {
  document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
}
  • 이를 checkBrn() 함수로 만든다.
function checkBrn() {
  var brn = document.getElementById( "brn" ).value;
  if ( /^[0-9]{3}-[0-9]{2}-[0-9]{5}$/.test( brn ) ) {
    document.getElementById( "checkBrnMessage" ).innerText = "OK";
  } else {
    document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
  }
}
  • 전체 코드는 다음과 같다.
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <style>
      * {
        font-family: Consolas, monospace;
        font-size: 20px;
      }
    </style>
  </head>
  <body>
    <p>
      <input type="text" name="brn" id="brn">
      <input type="button" value="Check" onclick="checkBrn();">
    </p>
    <p id="checkBrnMessage"></p>
    <script>
      function checkBrn() {
        var brn = document.getElementById( "brn" ).value;
        if ( /^[0-9]{3}-[0-9]{2}-[0-9]{5}$/.test( brn ) ) {
          document.getElementById( "checkBrnMessage" ).innerText = "OK";
        } else {
          document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
        }
      }
    </script>
  </body>
</html>

  • 형식에 맞게 입력하면 OK를 출력한다.

  • 형식에 맞지 않게 입력하면 NOT OK를 출력한다.

전화번호 유효성 검사

  • 000-0000-0000 형식의 전화번호인지 검사하고 싶다면 정규표현식을 /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/로 변경한다.
if ( /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/.test( brn ) ) {
  document.getElementById( "checkBrnMessage" ).innerText = "OK";
} else {
  document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
}
  • 010으로 시작하게 하려면 정규표현식을 /^010-[0-9]{4}-[0-9]{4}$/로 변경한다.
if ( /^010-[0-9]{4}-[0-9]{4}$/.test( brn ) ) {
  document.getElementById( "checkBrnMessage" ).innerText = "OK";
} else {
  document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
}

입력하는 순간 유효성 검사하기

  • jQuery를 이용하여 다음과 같이 하면, 폼을 선택하고 입력할 때마다 유효성 검사를 한다.
  • 즉, 010-0000-0000 형식이 되기 전까지는 NOT OK를, 입력을 마치는 순간 OK를 출력한다.
<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <style>
      * {
        font-family: Consolas, monospace;
        font-size: 20px;
      }
    </style>
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
  </head>
  <body>
    <p>
      <input type="text" name="brn" id="brn">
    </p>
    <p id="checkBrnMessage"></p>
    <script>
      $( '#brn' ).on( 'focus keyup', function() {
        var brn = document.getElementById( "brn" ).value;
        if ( /^010-[0-9]{4}-[0-9]{4}$/.test( brn ) ) {
          document.getElementById( "checkBrnMessage" ).innerText = "OK";
        } else {
          document.getElementById( "checkBrnMessage" ).innerText = "NOT OK";
        }
      } );
    </script>
  </body>
</html>
같은 카테고리의 다른 글
JavaScript / 반복문 / while, do - while, for

JavaScript / 반복문 / while, do - while, for

자바스크립트 반복문에는 while, do - while, for 세가지가 있습니다. while 문법 var i = 0; while ( i < 10 ) { // do something i++; } i의 값이 0부터 9일 때까지 실행되고 i의 값이 10이면 실행되지 않고 다음으로 넘어갑니다. i의 값을 증가시키는 i++을 꼭 넣어야 한다는 것에 주의해야 합니다. 만약 i++이 없으면 i의 값이 ...

JavaScript / window.open / 새 창 띄우기, 부모 창과 자식 창 사이 값 전달하기

JavaScript / window.open / 새 창 띄우기, 부모 창과 자식 창 사이 값 전달하기

window.open으로 새 창을 띄우고, 부모 창에서 자식 창으로, 자식 창에서 부모 창으로 값을 전달하는 방법을 정리한다. 부모 창이 parent.html, 자식 창이 child.html이다. 새 창 띄우기 문법은 다음과 같다. window.open( url, windowName, windowFeatures ); url : 새 창에 들어갈 문서 주소 windowName : 윈도우 이름 windowFeatures : 새 창의 특성 예를 들어 다음은... window.open( "child.html", "Child", "width=400, height=300, top=50, left=50" ...

JavaScript / Object / String.repeat() / 문자열을 반복한 값을 반환하는 메서드

JavaScript / Object / String.repeat() / 문자열을 반복한 값을 반환하는 메서드

.repeat() .repeat() – 문자열을 반복한 값을 반환하는 메서드입니다. IE는 Edge부터 지원합니다. 문법 string.repeat( count ) 예제 'abc'.repeat( 2 ) abc를 두 번 반복한 abcabc를 반환합니다.

JavaScript / 함수 / parseFloat(), parseInt() - 문자열을 수로 바꾸는 함수

JavaScript / 함수 / parseFloat(), parseInt() - 문자열을 수로 바꾸는 함수

parseFloat() parseFloat()는 문자열을 실수로 바꾸는 함수입니다. 문법 parseFloat( string ) 수로 시작할 때 그 수를 실수로 바꿉니다. 띄어 쓰기로 여러 개의 수가 있으면 첫번째 수만 바꿉니다. 공백으로 시작하면 공백은 무시합니다. 수가 아닌 문자로 시작하면 NaN을 반환합니다. 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> </head> <body> <script> document.write( "<p>parseFloat( '12.34' ) : " + parseFloat( '12.34' ) + "</p>" ); document.write( "<p>parseFloat( ' 12.34' ...

JavaScript / Object / document.characterSet / 문자 인코딩 반환하는 속성

JavaScript / Object / document.characterSet / 문자 인코딩 반환하는 속성

.characterSet .characterSet은 문서의 문자 인코딩을 반환하는 속성입니다. 예제 <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <title>JavaScript</title> <style> body { font-family: Consolas, monospace; } </style> </head> <body> <script> document.write( "<p>document.characterSet : " + document.characterSet + "</p>" ); </script> </body> </html>

JavaScript / Object / document.getElementsByTagName() / 특정 태그를 가진 요소 가져오는 메서드

JavaScript / Object / document.getElementsByTagName() / 특정 태그를 가진 요소 가져오는 메서드

.getElementsByTagName() .getElementsByTagName()는 특정 태그를 가진 모든 요소를 선택합니다. 선택된 요소는 유사 배열 객체로 반환됩니다. 문법 1 document.getElementsByTagName( 'tagname' ) 예를 들어 p 태그를 가진 첫번째 요소를 선택하려면 다음과 같이 합니다. document.getElementsByTagName( 'p' ) 예제 1 문서에서 p 태그를 가진 두번째 요소를 jb라는 변수에 넣고, 몇 가지 정보를 출력하는 예제입니다. <!doctype html> <html lang="ko"> <head> <meta ...

JavaScript / Plugin / Swiper / 슬라이더 플러그인

JavaScript / Plugin / Swiper / 슬라이더 플러그인

Swiper는 널리 사용되는 슬라이더 플러그인 중의 하나입니다. 다양한 옵션을 제공하며, 해상도에 따라 다른 옵션을 줄 수 있어 반응형 사이트에 사용하기 좋습니다. 홈페이지 : https://swiperjs.com/ GitHub : https://github.com/nolimits4web/swiper Swiper는 IE를 지원하지 않습니다. 만약 IE 지원이 중요하다면, IE를 지원하는 Swiper 구 버전을 사용하거나 다른 슬라이더를 사용하세요. 기본 사용법 스크립트 파일과 CSS 파일을 연결합니다. 다음은 CDN을 이용하여 연결하는 코드입니다. <script src="https://unpkg.com/swiper@7/swiper-bundle.min.js"></script> <link ...

JavaScript / Object / document.querySelectorAll() / 특정 CSS 선택자를 가진 모든 요소 선택하는 메서드

JavaScript / Object / document.querySelectorAll() / 특정 CSS 선택자를 가진 모든 요소 선택하는 메서드

.querySelectorAll() .querySelectorAll()은 특정 CSS 선택자를 가진 모든 요소를 배열로 가져오는 메서드입니다. 문법 document.querySelectorAll( 'selector' ) 예를 들어 document.querySelectorAll( '.abc' ) 는 클래스 값이 abc인 모든 요소를 가져옵니다. document.querySelectorAll( '.abc, .def' ); 클래스 값이 abc 또는 def인 모든 요소를 가져옵니다. 예제 1 클래스 값이 abc인 요소 중 두번째 요소의 색을 빨간색으로 만듭니다. <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> ...

JavaScript / Object / String.substr() / 문자열 추출하는 메서드

JavaScript / Object / String.substr() / 문자열 추출하는 메서드

.substr() .substr()은 문자열에서 특정 부분만 골라낼 때 사용하는 메서드입니다. 문법 string.substr( start, length ) start로 시작 위치를 정하고 length로 잘라낼 문자열의 길이를 정합니다. 예를 들어 var str = '123456789'; document.write( '<p>substring( 1, 5 ) : ' + str.substr( 1, 5 ) + '</p>' ); 는 23456을 출력합니다. start 값은 필수이고, length를 지정하지 않으면 문자열의 끝까지를 가져옵니다. 예제 <!doctype html> <html lang="ko"> ...

JavaScript / 주석(Comment) 넣기

JavaScript / 주석(Comment) 넣기

한 줄 주석 한 줄 주석은 //로 만듭니다. // single line comment // 앞은 코드로 처리하고, // 뒤는 주석으로 처리합니다. 예를 들어 var jb = 'hi'; // Comment 라고 var jb = 'hi';는 코드로 인식합니다. 여러 줄 주석 여러 줄을 주석으로 만들 때는 /*와 */로 둘러쌉니다. /* Comment 1 Comment 2 ​*/ 읽기 좋게 다음과 같은 모양으로 만들기도 ...