공부/JavaScript

Object Validation in JavaScript

Dev_YJ 2024. 9. 30. 14:59

1. hasOwnProperty Method

const user = {
  name: "John Doe",
  email: "john@example.com",
};
// Check if 'user' object has 'email' property
if (user.hasOwnProperty("email")) {
  console.log("User has an email property.");
} else {
  console.log("User does not have an email property.");
}

 

2. typeof Operator

const product = {
  name: "Widget",
  price: 19.99,
};
// Check the data type of the 'price' property
if (typeof product.price === "number") {
  console.log("Price is a number.");
} else {
  console.log("Price is not a number.");
}

typeof 가 반환 할 수 있는 값 : Undefined, Null, Boolean, Number, Bigint, String, Symbol, host객체, Function 객체, object

 

3. instanceof Operator

instanceof 연산자는 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별

class CustomObject {
  constructor() {
    this.property = "Custom Property";
  }
}
const obj = new CustomObject();
// Check if 'obj' is an instance of 'CustomObject' class
if (obj instanceof CustomObject) {
  console.log("obj is an instance of CustomObject.");
} else {
  console.log("obj is not an instance of CustomObject.");
}

 

4. Validating with Object.keys

const person = {
  firstName: "John",
  lastName: "Doe",
};
const requiredFields = ["firstName", "lastName", "email"];

// Check if 'person' object contains all required fields
const isValid = requiredFields.every((field) => 
Object.keys(person).includes(field));

if (isValid) {
  console.log("Person object is valid.");
} else {
  console.log("Person object is missing required fields.");
}

 

5. Crafting Custom Validation Functions

function isEmailValid(email) {
  // Regular expression for validating email addresses
  const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  // Use the 'test' method of the regex to validate 'email' input
  return emailRegex.test(email);
}
 const userInput = "invalid-email";
// Check if 'userInput' is a valid email
if (isEmailValid(userInput)) {
  console.log("Email is valid.");
} else {
  console.log("Email is invalid.");
}

 

참고

https://medium.com/@stheodorejohn/object-validation-in-javascript-best-practices-and-examples-112855955566

 

Object Validation in JavaScript — Best Practices and Examples

🔍 Explore advanced JavaScript object validation. Elevate your JavaScript skills! Dive into robust object validation now. “🚀 #JavaScript…

medium.com

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/typeof

 

typeof - JavaScript | MDN

typeof 연산자는 피연산자의 평가 전 자료형을 나타내는 문자열을 반환합니다.

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/instanceof

 

instanceof - JavaScript | MDN

instanceof 연산자는 생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별합니다.

developer.mozilla.org