빈 입력 필드에 대한 JavaScript 유효성 검사


95

<input name="question"/>제출 버튼을 클릭하여 제출할 때 IsEmpty 함수를 호출하고 싶은 이 입력 필드가 있습니다.

아래 코드를 시도했지만 작동하지 않았습니다. 어떤 충고?

<html>

<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=unicode" />
  <meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />
</head>

<body>


  <script language="Javascript">
    function IsEmpty() {

      if (document.form.question.value == "") {
        alert("empty");
      }
      return;
    }
  </script>
  Question: <input name="question" /> <br/>

  <input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />

</body>

</html>


잘못된 답변을 수락했습니다 . 입력 (또는 텍스트 영역)이 항상 문자열을 반환하기 때문에 null을 확인하는 것은 홀수입니다. 또한 인라인 JavaScript를 사용해서는 안됩니다. 또한 맹목적으로 사용해서는 안됩니다 return false... etc etc
Roko C. Buljan

답변:


122

<script type="text/javascript">
  function validateForm() {
    var a = document.forms["Form"]["answer_a"].value;
    var b = document.forms["Form"]["answer_b"].value;
    var c = document.forms["Form"]["answer_c"].value;
    var d = document.forms["Form"]["answer_d"].value;
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
      alert("Please Fill All Required Field");
      return false;
    }
  }
</script>

<form method="post" name="Form" onsubmit="return validateForm()" action="">
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>


2
'onsubmit = "return validate ()"'를 변경해야합니다. validate는 함수의 이름이 아닙니다. 'onsubmit = "return validateForm ()"'
이어야합니다.

3
대답과 OP의 의심을 설명하는 것이 가장 좋습니다.
Vishal

7
이것은 실제로 유효하지 않습니다. if명령문 의 쉼표로 인해 마지막 검사 만 반환됩니다. stackoverflow.com/a/5348007/713874
Bing

35

여기에서 작동 예를 참조하십시오.


필수 <form>요소 가 누락되었습니다 . 코드는 다음과 같습니다.

function IsEmpty() {
  if (document.forms['frm'].question.value === "") {
    alert("empty");
    return false;
  }
  return true;
}
<form name="frm">
  Question: <input name="question" /> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>


양식의 모든 필드에 대해이 작업을 수행하는 방법이 있습니까?
스페어 사이클

34

입력 필드 에는 공백이있을 수 있으므로 이를 방지하고 싶습니다.
사용 String.prototype.trim () :

function isEmpty(str) {
    return !str.trim().length;
}

예:

const isEmpty = str => !str.trim().length;

document.getElementById("name").addEventListener("input", function() {
  if( isEmpty(this.value) ) {
    console.log( "NAME is invalid (Empty)" )
  } else {
    console.log( `NAME value is: ${this.value}` );
  }
});
<input id="name" type="text">


1
null 및 ""외에이 부분도 누락되었습니다. 그것은 나를 위해 일했습니다. 감사합니다 Roko.
Pedro Sousa

17

사용자가 자바 스크립트를 비활성화 한 경우 필수 속성을 추가하고 싶습니다.

<input type="text" id="textbox" required/>

모든 최신 브라우저에서 작동합니다.


10
if(document.getElementById("question").value.length == 0)
{
    alert("empty")
}

7

입력 요소에 ID "질문"을 추가 한 후 다음을 시도하십시오.

   if( document.getElementById('question').value === '' ){
      alert('empty');
    }

현재 코드가 작동하지 않는 이유는 거기에 FORM 태그가 없기 때문입니다. 또한 "이름"을 사용한 조회는 더 이상 사용되지 않으므로 권장되지 않습니다.

이 게시물에서 @Paul Dixon의 답변을 참조하십시오 : 'name'속성이 <a> 앵커 태그에 대해 오래된 것으로 간주됩니까?


1
if(document.getElementById("question").value == "")
{
    alert("empty")
}

1
... <input>요소 에 "id"속성이 없습니다 . IE가 고장 났기 때문에 IE에서만 작동합니다.
Pointy

죄송합니다. ID, document.getElementsByName ( "question") [0] .value가 있다고 생각했거나 요소에 ID를 추가하십시오
Kenneth J

1

입력 요소에 ID 태그를 추가하기 만하면됩니다. 예 :

자바 스크립트에서 요소의 값을 확인하십시오.

document.getElementById ( "question"). value

아, 파이어 폭스 / 방화범을 가져와. 자바 스크립트를 수행하는 유일한 방법입니다.


0

내가 사용했기 때문에 내 솔루션은 다음과 ES6에 const당신은 당신이 모두를 대체 할 수 ES5 원하는 경우 const에를 var.

const str = "       Hello World!        ";
// const str = "                     ";

checkForWhiteSpaces(str);

function checkForWhiteSpaces(args) {
    const trimmedString = args.trim().length;
    console.log(checkStringLength(trimmedString))     
    return checkStringLength(trimmedString)        
}

// If the browser doesn't support the trim function
// you can make use of the regular expression below

checkForWhiteSpaces2(str);

function checkForWhiteSpaces2(args) {
    const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
    console.log(checkStringLength(trimmedString))     
    return checkStringLength(trimmedString)
}

function checkStringLength(args) {
    return args > 0 ? "not empty" : "empty string";
}


0

<pre>
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
           <input type="text"   id="name"   name="name" /> 
           <input type="submit"/>
       </form>
    </pre>

<script language="JavaScript" type="text/javascript">
  var frmvalidator = new Validator("myform");
  frmvalidator.EnableFocusOnError(false);
  frmvalidator.EnableMsgsTogether();
  frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>

위 코드를 사용하기 전에 gen_validatorv31.js 파일 을 추가 해야 합니다.


0

모든 접근 방식을 결합하면 다음과 같이 할 수 있습니다.

const checkEmpty = document.querySelector('#checkIt');
checkEmpty.addEventListener('input', function () {
  if (checkEmpty.value && // if exist AND
    checkEmpty.value.length > 0 && // if value have one charecter at least
    checkEmpty.value.trim().length > 0 // if value is not just spaces
  ) 
  { console.log('value is:    '+checkEmpty.value);}
  else {console.log('No value'); 
  }
});
<input type="text" id="checkIt" required />

진정으로 값을 확인하려면 서버에서 수행해야하지만 이것은이 질문의 범위를 벗어납니다.


0

제출 후 각 입력을 반복하고 비어 있는지 확인할 수 있습니다.

let form = document.getElementById('yourform');

form.addEventListener("submit", function(e){ // event into anonymous function
  let ver = true;
  e.preventDefault(); //Prevent submit event from refreshing the page

  e.target.forEach(input => { // input is just a variable name, e.target is the form element
     if(input.length < 1){ // here you're looping through each input of the form and checking its length
         ver = false;
     }
  });

  if(!ver){
      return false;
  }else{
     //continue what you were doing :)
  } 
})

0

<script type="text/javascript">
  function validateForm() {
    var a = document.forms["Form"]["answer_a"].value;
    var b = document.forms["Form"]["answer_b"].value;
    var c = document.forms["Form"]["answer_c"].value;
    var d = document.forms["Form"]["answer_d"].value;
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
      alert("Please Fill All Required Field");
      return false;
    }
  }
</script>

<form method="post" name="Form" onsubmit="return validateForm()" action="">
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>


안녕하세요, 솔루션을 제공 할 때 솔루션이 향후 독자에게 도움이 될 수있는 문제를 해결하는 이유를 제공하는 것이 좋습니다.
Ehsan Mahmud
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.