쌍용교육(JAVA)/JavaScript

쌍용교육 -JavaScript수업 39일차 JSRegular

구 승 2024. 4. 15. 14:18

s01_regular.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>정규표현식</title>
<script type="text/javascript">
/* 
정규표현식(regular expression)은 일정한 패턴을 가진 문자열의 집합을 표현하기 위해서 사용하는 형식언어(formal language)이다.
*/
window.onload = function(){
	const form = document.getElementById('register_form');
	//이벤트 연결
	form.onsubmit = function(){
		const phone = document.getElementById('phone');
		/* 
		/패턴/ -> /(시작) 패턴 /(끝)
		^ 패턴의 시작
		\\d : 숫자
		{3} : 3번 반복
		$ 패턴의 끝
		*/
		//test(문자열) : 정규표현식이 매개변수로 전달된 문자열과 패턴 일치하면 true, 불일치하면 false 인 test메서드
			//슬레쉬 안에 값들은 객체로 인식함
		if(!/^\\d{3}-\\d{4}-\\d{4}$/.test(phone.value)){//불일치하면 if블럭으로 들어와야되기 때문에 앞에 !를 써준다. 
			alert('000-0000-0000 형식으로 입력하세요!');
			phone.value ='';
			phone.focus();
			return false; //submit이기 때문에 false를 써준다.
		}
	};
};
</script>
</head>
<body>
<h3>정규표현식</h3>
<form id="register_form" action="a.jsp" method="post">
	<ul>
		<li>
			<label for="phone">휴대폰</label>
			<input type="text" name="phone" id="phone">
			(000-0000-0000 형식으로 입력)
		</li>
	</ul>
	<div>
		<input type="submit" value="전송">
	</div>
</form>
</body>
</html>

 

s02_regular.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>정규표현식</title>
<script type="text/javascript">
window.onload = function(){
	const form = document.getElementById('register_form');
	//이벤트 연결
	form.onsubmit = function(){
	const phone = document.getElementById('phone');
	/* 
	/패턴/ -> /(시작) 패턴 /(끝)
	^ 패턴의 시작
		[] '[' 와 ']' 사이의 문자들과 매치라는 의미
		[]안의 문자 사이에 하이폰(-)을 사용하게 되면 문자 사이의 범위(From-To)를 의미
		[0-9]: ->[0123456789]와 같은 의미
		{11} : 11번 반복
		$ 패턴의 끝
		*/
		//match : test보다 느림, 일치하면 검색 데이터를 반환, 불일치 null 반환
		if(!phone.value.match(/^[0-9]{11}$/)){
			alert('11자리 숫자만 입력가능');
			phone.value = '';
			phone.focus();
			return false;
		}
	};
};
</script>
</head>
<body>
<h3>정규표현식</h3>
<form id="register_form" action="a.jsp" method="post">
	<ul>
		<li><label for="phone">휴대폰</label> 
		<input type="text" name="phone" id="phone"> (-없이 입력)</li>
	</ul>
	<div>
		<input type="submit" value="전송">
	</div>
	</form>
</body>
</html>

 

s03_regular.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>정규표현식</title>
<script type="text/javascript">
window.onload = function(){
	const form = document.getElementById('register_form');
	//이벤트 연결
	form.onsubmit = function(){
	const id = document.getElementById('id');
	/* 
	/패턴/ -> /(시작) 패턴 /(끝)
	^ 패턴의 시작
	[] '[' 와 ']' 사이의 문자들과 매치라는 의미	
	[A-Za-z0-9] -> A~Z,a~z,0~9
	{4~12} 반복횟수가 4부터 12까지
	$ 패턴의 끝
	*/
	if(!/^[A-Za-z0-9]{4,12}$/.test(id.value)){
		alert('영문 또는 숫자 사용, 최소4자~최대 12자를 사용하세요');
		id.value='';
		id.focus();
		return false;
		
		
	}
	
	};
};
</script>
</head>
<body>
<h3>정규표현식</h3>
<form id="register_form" action="a.jsp" method="post">
	<ul>
		<li><label for="id">아이디</label> 
		<input type="text" name="id" id="id"> (영문 또는 숫자 사용, 최소 4자 ~최대 12자)</li>
	</ul>
	<div>
		<input type="submit" value="전송">
	</div>
	</form>
</body>
</html>