Walidacja JavaScript dla pustego pola wejściowego


97

Mam to pole wejściowe, <input name="question"/>które chcę wywołać funkcję IsEmpty po przesłaniu, klikając przycisk przesyłania.

Wypróbowałem poniższy kod, ale nie zadziałał. jakakolwiek rada?

<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>


Przyjąłeś nieprawidłową odpowiedź . Sprawdzanie wartości null jest nieparzyste, ponieważ dane wejściowe (lub obszar tekstowy) zawsze zwracają ciąg. Nie powinieneś także używać wbudowanego JavaScript. Nie powinieneś też używać na ślepo return false... itd. Itd.
Roko C. Buljan

Odpowiedzi:


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 () "'wymaga zmiany. validate nie jest nazwą funkcji. Powinien to być „onsubmit =" return validateForm () "'
tazboy

3
Najlepiej byłoby wyjaśnić odpowiedź i wątpliwości OP.
Vishal

7
To zaakceptowane jest w rzeczywistości nieważne. Przecinki w ifinstrukcji spowodują zwrócenie tylko ostatniego czeku: stackoverflow.com/a/5348007/713874
Bing

35

Zobacz przykład roboczy tutaj


Brakuje wymaganego <form>elementu. Oto jak powinien wyglądać Twój kod:

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>


Czy można to zrobić dla wszystkich pól w formularzach?
rower zapasowy

35

Pole wejściowe może zawierać spacje , chcemy temu zapobiec.
Użyj String.prototype.trim () :

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

Przykład:

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
Oprócz null i „”, w moim kodzie brakowało również tego elementu. U mnie zadziałało. Dzięki Roko.
Pedro Sousa

17

Chciałbym dodać wymagany atrybut na wypadek wyłączenia javascript przez użytkownika:

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

Działa na wszystkich nowoczesnych przeglądarkach.


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

7

Dodaj identyfikator „pytanie” do elementu wejściowego, a następnie spróbuj tego:

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

Twój obecny kod nie działa, ponieważ nie masz w nim tagu FORM. Ponadto wyszukiwanie przy użyciu „nazwy” nie jest zalecane, ponieważ jest przestarzałe.

Zobacz odpowiedź @Paul Dixon w tym poście: Czy atrybut „name” jest uważany za nieaktualny dla <a> tagów kotwicy?


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

1
... nie ma atrybutu „id” w <input>elemencie; działałoby to tylko w IE, ponieważ IE jest uszkodzony.
Pointy

przepraszam, myślałem, że istnieje ID, document.getElementsByName ("question") [0] .value, lub po prostu dodaj identyfikator do elementu
Kenneth J

1

Po prostu dodaj identyfikator do elementu wejściowego ... tj .:

i sprawdź wartość elementu w swoim javascript:

document.getElementById ("pytanie"). wartość

O tak, pobierz firefox / firebug. To jedyny sposób na wykonanie javascript.


0

Poniżej moje rozwiązanie jest w ES6 bo wykorzystały constjeśli wolisz ES5 można zastąpić wszystko constz 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>

przed użyciem powyższego kodu musisz dodać plik gen_validatorv31.js


0

Łącząc wszystkie podejścia, możemy zrobić coś takiego:

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 />

Zauważ, że jeśli naprawdę chcesz sprawdzić wartości, powinieneś to zrobić na serwerze, ale to jest poza zakresem tego pytania.


0

Możesz przejrzeć każde wejście po przesłaniu i sprawdzić, czy jest puste

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>


Cześć, kiedy zapewniasz rozwiązanie, byłoby wspaniale podać powód, dla którego twoje rozwiązanie rozwiązuje problem, co może pomóc przyszłym czytelnikom.
Ehsan Mahmud
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.