< Code diaries />

[HTML] input 패턴 정규표현식. html 입력필드에 들어가는 값에 대한 표현식 정하기. RegExp in javascript 본문

Html

[HTML] input 패턴 정규표현식. html 입력필드에 들어가는 값에 대한 표현식 정하기. RegExp in javascript

ejey 2024. 1. 25. 04:10

 

 

 

html의 input태그에 pattern속성을 이용하여 입력받는 텍스트를 제어할수 있다.

css를 이용하여 패턴식에 맞지않을때에 style 처리도 가능하다.

이는 HTML5 에 추가된 속성이다.

 

 

Input pattern 정규표현식 기본사용법

[ html 코드 ]
<input type="text" pattern="[0-9]+" placeholder="input"> 
<!-- 숫자만 입력가능 -->

[ css 코드 ]
input:invalid { color:red }
/* 패턴과 일치하지않을경우 박스에 안내가 표시되며, 글자색은 레드로 바뀐다 */

 

 

The pattern attribute is an attribute of the texttelemailurlpassword, and search input types.

패턴 속성은 input의  text, email, url, password,search types에 사용할 수 있다.

 

The pattern attribute, when specified, is a regular expression which the input's value must match for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions.

패턴속성이 지정된 경우에는, 입력값과 일치해야 검증을 통과할 수 있는 정규 표현식이다.

javascript에서 사용하는 유효한 RegExp 정규표현식이어야 한다. 

패턴주변에 javascript처럼 슬래시를 지정하지 않아야 하며, 비어있거나, 유효하지않은 값일 경우 정규식이 적용되지 않는다.

 
패턴 속성을 지원하는 일부 입력 유형, 특히 e-메일 및 url 입력 유형에는 일치해야 하는 예상 값 구문이 있습니다. 패턴 속성이 없고 값이 해당 값 유형의 예상 구문과 일치하지 않으면 ValidityState 개체의 읽기 전용 typeMismatch 속성이 true가 됩니다.

 

 

최소글자수, 최대글자수 지정

<input type="text" minlength="5" maxlength="10" pattern="^[0-9]+">

 

0~9까지의 숫자로 시작하는 입력값만 받으며 글자수는 5~10자 범위내에서 가능하다.

 

정규식표현 - String Class

Meta String description Meta String desciption
[.] . . 모든 문자
[0-9] 0부터9까지 숫자지정    
[x] x x x
[xy] x or y x|y x or y
[a-z] a-z까지 소문자    
[A-Z] A-Z까지 대문자 x? x를 0 또는 1이상 반복
^[x] x로 시작한다 ^x x로 시작한다
[x]$ x로 끝난다 x$ x로 끝난다
[^x] x가 아닌것 x* x문자열이 0개 이상이다(필수아님)
[가-힣] 한글 x+ x문자열이 1개 이상이다(1개는 필수)
() ()안에있는 문자들의 그룹화  x{n} x문자열의 개수지정
    x{n,} x문자열의 개수를 n개 이상으로 지정
    x{n,m} x문자열의 개수의 범위지정(n부터 m개수까지)

 

정규식표현 - Escape

name description name desciption
\d 숫자 == [0-9] \D 숫자가 아니다 == [^0-9]
\w 숫자,영문,밑줄 \W 숫자,영문,밑줄이 아니다.
\s 공백 == [\t\n] \S 공백이 아니다. == [^\s]

 

 

많이쓰는 정규식 모음

 

숫자만 입력받기

pattern="\d*" <!-- \d : 숫자만 입력받겠다. * : 반복입력가능 -->

 

휴대폰 번호 등 숫자외에 하이픈등을 입력받고 싶지 않을때 사용. * 은 숫자를 0번이상 반복한다.

글자수 제한은 위의 minlength, maxlength지정과 같이 사용하면 좋을 듯하다.

 

영문 소문자 2~4글자 입력받기

pattern="[a-z]{2,4}" <!-- 영문소문자로 2~4자 입력허용 -->

 

우편번호 입력받기

pattern="[0-9]{5}" <!-- 숫자 5자리  -->

 

 

이름 입력받기

pattern="^[가-힣]{3,4}|[a-zA-Z]{3,12}"

 

 

 

 

 

[ Referece of MDN ] 

 

HTML attribute: pattern - HTML: HyperText Markup Language | MDN

The pattern attribute specifies a regular expression the form control's value should match. If a non-null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true.

developer.mozilla.org

반응형