Javascript

form selector 유효성점검 submit

아이티프로 2023. 1. 24.
반응형
<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <br>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" required>
  <br>
  <button type="submit">Submit</button>
</form>
let form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
  event.preventDefault(); // prevent the form from submitting
  let valid = true;
  let inputs = form.getElementsByTagName("input");
  for (let i = 0; i < inputs.length; i++) {
    if (!inputs[i].checkValidity()) {
      valid = false;
      break;
    }
  }
  if (!valid) {
    alert("Please fill out all fields.");
  } else {
    alert("Form Submitted!");
    form.submit(); // submit the form
  }
});

 

 

 

DOM selector

DOM(document object model)에서 객체를 선택적으로 가져온다.

// id 셀렉터

let form = document.getElementById("myForm");

// tag 셀렉터

let inputs = form.getElementsByTagName("input");

// name 셀렉터

let elements = document.getElementsByName("myName");

// class 셀렉터

let elements = document.getElementsByClassName("myClass");

// query 셀렉터

let element = document.querySelector("#myId .myClass");

// query all 셀렉터
let elements = document.querySelectorAll("p.myClass");

 

event listener

event기반으로 개발하기위해 이벤트리스너를 사용하며 이벤트기반 함수를 이벤트핸들러라 부른다.

form.addEventListener("submit", function(event) {
  event.preventDefault(); // prevent the form from submitting

  ..
});

 

Validatation (유효성)

email 유효성

let email = document.getElementById("email").value;
let emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

if (!emailRegex.test(email)) {
    alert("Invalid email address");
}

 

password 유효성

let password = document.getElementById("password").value;
let passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;

if (!password.match(passwordRegex)) {
    alert("패스워드는 8자이상으로 대문자 한자이상, 소문자 한자이상, 숫자 한자이상이 포함되어야 한다.");
}

정규효현식을 사용하여 패스워드는 8자이상으로 대문자 한자이상, 소문자 한자이상, 숫자 한자이상이 포함되어야 한다. 여부를 match시켜서 확인한다.

let password = document.getElementById("password").value;
let confirmPassword = document.getElementById("confirmPassword").value;

if (password !== confirmPassword) {
    alert("Passwords do not match");
}

두개의 패스워드 박스에서 입력한 값이 일치하는 지 점검

 

selectbox 유효성

let select = document.getElementById("mySelect");

if (select.selectedIndex <= 0) {
    alert("Please select an option");
}

if (select.selectedIndex <= 0) 이다라는 것은 selectbox가 선택이 안 되었다는 것이다. 선택이되면 1이상이 된다.

 

checkbox 유효성

let checkbox = document.getElementById("myCheckbox");

if (!checkbox.checked) {
    alert("Please check the checkbox");
}

if (!checkbox.checked) 이다라는 것은 checkbox가 체크가 안되었다는 뜻이다.

 

file upload 유효성

file.type으로 업로드가능한 화이트리스트에 해당하는 지 점검

file.size로 파일크기 확인 후 업로드용량제한 초과 점검

let fileInput = document.getElementById("myFile");
let file = fileInput.files[0];

// allowed file types
let allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
// allowed file size (in bytes)
let maxSize = 1000000; // 1 MB

// check file type
if (!allowedTypes.includes(file.type)) {
    alert("Invalid file type. Only jpeg, png, pdf files are allowed.");
    fileInput.value = ""; // clear the selected file
} 
// check file size
else if (file.size > maxSize) {
    alert("File is too large. Maximum allowed size is 1MB.");
    fileInput.value = ""; // clear the selected file
} 
// file is valid
else {
    // submit the file
}

 

파일 확장자로 업로드가능한 화이트리스트에 해당하는 지 점검

let fileInput = document.getElementById("myFile");
let file = fileInput.files[0];

// allowed file extensions
let allowedExtensions = ['.jpg', '.jpeg', '.png', '.pdf'];

// get the file extension
let fileName = file.name;
let fileExtension = fileName.substring(fileName.lastIndexOf('.'));

// check if the file extension is in the list of allowed extensions
if (!allowedExtensions.includes(fileExtension)) {
    alert("Invalid file extension. Only jpg, jpeg, png, pdf files are allowed.");
    fileInput.value = ""; // clear the selected file
} else {
    // submit the file
}

fileExtension = fileName.substring(fileName.lastIndexOf('.')) 을 사용해 확장자를 구할 수 있다.

test.jpg의 lastIndexOf('.')는 4이다. fileName.substring(4)의 결과는 ".jpg"이다.

그러므로 배열의 includes 매서드를 통해 포함여부를 체크해보니 업로드가 가능한 파일이다.

그러나 확장자는 바꿀 수 있으므로 서버측에서는 별도의 대비가 필요하다.

 

반응형

'Javascript' 카테고리의 다른 글

Map set Iterating  (0) 2023.01.24
날짜 객체 new Date()  (0) 2023.01.24
연산자 우선순위  (0) 2023.01.24
에러 처리 & 디버깅  (0) 2023.01.24
Arrow function 화살표함수  (0) 2023.01.24

댓글