차곡차곡

[TypeScript] 1. Form Validator 본문

Language/TypeScript

[TypeScript] 1. Form Validator

sohy 2023. 2. 21. 19:24

✨ 1. Form Validator ✨

 

GitHub - bradtraversy/vanillawebprojects: Mini projects built with HTML5, CSS & JavaScript. No frameworks or libraries

Mini projects built with HTML5, CSS & JavaScript. No frameworks or libraries - GitHub - bradtraversy/vanillawebprojects: Mini projects built with HTML5, CSS & JavaScript. No frameworks or l...

github.com

 

구현

  • checkRequired() : input 값 확인
  • checkLength() : 입력 값 길이 확인 ( username 3 이상 15 이하, password 6 이상 25 이하 )
  • checkEmail() : 이메일 정규식 확인
  • checkPasswordsMatch() : 입력한 비밀번호 두 개가 동일한지 확인

→ 조건에 부합하지 않을 시 error css 노출

 

배운점

  • typescript는 type-safe 언어이기 때문에 document.getElementById() 함수 사용 시 HTMLElement 타입을 반환해서 text의 value 프로퍼티 값을 바로 읽을 수가 없다. 따라서, value 프로퍼티 값을 읽어오기 위해선 아래처럼 타입 캐스팅을 해주어야 한다.
let textElement = <HTMLInputElement>document.getElementById('username'); 
let value = textElement.value;
  • form 안에 submit 역할을 하는 버튼을 눌렀어도 새로 실행하지 않게 하고싶을 경우 (submit은 작동됨) event.preventDefault() 함수를 사용해준다.
  • 이메일 정규식
let regExp =/^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;
	if (email.value.match(regExp) != null) {
		success(1);
	} else {
		error(1, "Email is not valid");
	}
  • class 추가
element.className = "form-control error";

 

느낀점

자바스크립트를 거의 다 까먹어서 dom 요소를 어떻게 가져올지, class를 어떻게 추가할지 다 검색해서 해결할 수 있었다. 😰

 

참고

https://m.blog.naver.com/cjh7163/220696204552

https://programming119.tistory.com/100

https://solbel.tistory.com/375

 

Comments