본문 바로가기
Web/HTML

[HTML] 폼 필수 입력 메시지 변경 방법(form required message customizing)

by daewooki 2021. 8. 19.
반응형

 

HTML form에서 input이나 select를 필수로 하게 해야할 때가 있다. 

태그 내부에 required를 사용해주면 값이 입력이 되지 않으면 알림이 오게 된다. 

 

다음은 HTML 소스와  해당 페이지 결과이다.

 

<HTML>

<!DOCTYPE html>
<html>
<body>

<h1>The select required attribute</h1>

<p>The required attribute specifies that the user is required to select a value before submitting the form:</p>

<form action="/action_page.php">
  <label for="cars">Choose a car:</label>
  <select name="cars" id="cars" required>
    <option value="">None</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>

<페이지>

 

이 때 None으로 되어있는 옵션의 value는 ''로 비어있다. 

이 때 select 콤보박스는 required 옵션이 있어서 값이 없는 경우에는 알림이 뜬다. 

이 때 따로 메시지를 지정해주지 않은 경우에는 아래와 같이 뜬다. 

 

디폴트로 "목록에서 항목을 선택하세요" 라고 나오는데 이 메시지를 변경하고 싶을 때는 아래와 같이 작성해주면 된다. 

태그 내부에 required와 함께 oninvalid, oninput 옵션을 작성해주어야한다. oninvalid에는 값이 선택되지 않거나 입력이 되지 않았을 때 등장하는 메시지이고 oninput은 값이 입력되거나 선택되었을 때 발생하는 메시지로 비워두면 된다.

 

oninvalid="this.setCustomValidity('Please select the item.')" 
oninput="this.setCustomValidity('Okay')

 

<전체 HTML 소스>

<!DOCTYPE html>
<html>
<body>

<h1>The select required attribute</h1>

<p>The required attribute specifies that the user is required to select a value before submitting the form:</p>

<form action="/action_page.php">
  <label for="cars">Choose a car:</label>
  <select name="cars" id="cars" required 
    oninvalid="this.setCustomValidity('Please select the item.')" 
    oninput="this.setCustomValidity('')">
    <option value="">None</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>

 

<결과 페이지>

 

다음과 같이  Please select the item이라고 나오는 것을 확인할 수 있다. 

 

 

반응형

댓글