การตรวจสอบความถูกต้องของ JavaScript สำหรับฟิลด์อินพุตว่าง


100

ฉันมีช่องป้อนข้อมูลนี้ <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>


คุณได้รับการยอมรับคำตอบที่ไม่ถูกต้อง การตรวจสอบค่าว่างเป็นค่าคี่เนื่องจากอินพุต (หรือพื้นที่ข้อความ) จะส่งคืนสตริงเสมอ นอกจากนี้คุณไม่ควรใช้ JavaScript แบบอินไลน์ นอกจากนี้คุณไม่ควรใช้สุ่มสี่สุ่มห้าreturn false... ฯลฯ ฯลฯ
Roko C. Buljan

คำตอบ:


124

<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 ()"' จำเป็นต้องเปลี่ยน ตรวจสอบความถูกต้องไม่ใช่ชื่อของฟังก์ชัน ควรเป็น 'onsubmit = "return validateForm ()"'
tazboy

3
จะเป็นการดีที่สุดที่จะอธิบายคำตอบและข้อสงสัยของ OP
Vishal

7
สิ่งที่ยอมรับนี้ไม่ถูกต้องจริง เครื่องหมายจุลภาคในifคำสั่งจะทำให้เฉพาะการตรวจสอบล่าสุดเท่านั้นที่จะส่งคืน: stackoverflow.com/a/5348007/713874
Bing

36

ดูตัวอย่างการทำงานที่นี่


คุณไม่มี<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>


มีวิธีดำเนินการกับทุกช่องในรูปแบบหรือไม่
อะไหล่

35

ช่องป้อนข้อมูลสามารถมีช่องว่างได้เราต้องการป้องกันสิ่งนั้น
ใช้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
นอกจากค่าว่างและ "" รหัสของฉันฉันก็ยังขาดชิ้นส่วนนี้ด้วย มันได้ผลสำหรับฉัน ขอบคุณ Roko
Pedro Sousa

17

ฉันต้องการเพิ่มแอตทริบิวต์ที่จำเป็นในกรณีที่ผู้ใช้ปิดการใช้งานจาวาสคริปต์:

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

ใช้งานได้กับเบราว์เซอร์ที่ทันสมัยทั้งหมด



7

เพิ่มรหัส "คำถาม" ในองค์ประกอบอินพุตของคุณแล้วลองทำสิ่งนี้:

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

สาเหตุที่โค้ดปัจจุบันของคุณใช้ไม่ได้เนื่องจากคุณไม่มีแท็ก FORM อยู่ในนั้น นอกจากนี้ไม่แนะนำให้ค้นหาโดยใช้ "ชื่อ" เนื่องจากเลิกใช้แล้ว

ดูคำตอบของ @Paul Dixon ในโพสต์นี้: แอตทริบิวต์ "name" ถือว่าล้าสมัยสำหรับแท็ก <a> anchor หรือไม่


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

1
... ไม่มีแอตทริบิวต์ "id" ใน<input>องค์ประกอบ สิ่งนี้จะใช้ได้เฉพาะใน IE เนื่องจาก IE เสีย
Pointy

ขอโทษฉันคิดว่ามี ID, document.getElementsByName ("question") [0] .value หรือแค่เพิ่ม ID ให้กับองค์ประกอบ
Kenneth J

1

เพียงเพิ่มแท็ก ID ในองค์ประกอบอินพุต ... เช่น:

และตรวจสอบค่าขององค์ประกอบในคุณ javascript:

document.getElementById ("คำถาม"). value

โอ้รับ firefox / firebug มันเป็นวิธีเดียวที่จะทำจาวาสคริปต์


0

วิธีการแก้ปัญหาด้านล่างของฉันอยู่ใน ES6 เพราะผมได้ใช้constถ้าคุณต้องการ ES5 คุณสามารถแทนที่ทั้งหมดด้วยconstvar

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.