Convalida JavaScript per campo di input vuoto


95

Ho questo campo di input <input name="question"/>che desidero chiamare la funzione IsEmpty quando invio facendo clic sul pulsante di invio.

Ho provato il codice seguente ma non ha funzionato. qualche consiglio?

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


Hai accettato una risposta non valida . Il controllo di null è strano poiché un input (o textarea) restituisce sempre una stringa. Inoltre, non dovresti usare JavaScript inline. Inoltre non dovresti usare ciecamente return false... ecc ecc
Roko C. Buljan

Risposte:


121

<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 ()"' deve essere modificato. validate non è il nome della funzione. Dovrebbe essere 'onsubmit = "return validateForm ()"'
tazboy

3
Sarebbe meglio spiegare la risposta e il dubbio di OP.
Vishal

7
Questo accettato non è effettivamente valido. Le virgole nell'istruzione ifcauseranno la restituzione solo dell'ultimo assegno: stackoverflow.com/a/5348007/713874
Bing

35

Vedi l'esempio di lavoro qui


Ti manca l' <form>elemento richiesto . Ecco come dovrebbe essere il tuo codice:

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>


C'è un modo per farlo per tutti i campi nei moduli?
sparecycle

34

Un campo di input può avere spazi bianchi , vogliamo impedirlo.
Usa String.prototype.trim () :

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

Esempio:

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
Oltre a null e "", il mio codice mi mancava anche questo pezzo. Ha funzionato per me. Grazie Roko.
Pedro Sousa

17

Vorrei aggiungere l'attributo richiesto nel caso in cui l'utente disabiliti javascript:

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

Funziona su tutti i browser moderni.


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

7

Aggiungi una "domanda" id al tuo elemento di input e poi prova questo:

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

Il motivo per cui il tuo codice attuale non funziona è perché non hai un tag FORM. Inoltre, la ricerca utilizzando "nome" non è consigliata in quanto obsoleta.

Vedi la risposta di @Paul Dixon in questo post: l'attributo 'nome' è considerato obsoleto per i tag di ancoraggio <a>?


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

1
... non c'è nessun attributo "id" <input>sull'elemento; questo funzionerebbe solo in IE perché IE è rotto.
Pointy

scusa, pensavo ci fosse un ID, document.getElementsByName ("question") [0] .value, o semplicemente aggiungi un ID all'elemento
Kenneth J

1

Basta aggiungere un tag ID all'elemento di input ... cioè:

e controlla il valore dell'elemento nel tuo javascript:

document.getElementById ("question"). value

Oh sì, scarica firefox / firebug. È l'unico modo per eseguire javascript.


0

La mia soluzione di seguito è in es6 perché ho utilizzato constse preferisci es5 puoi sostituire tutto constcon 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>

prima di utilizzare il codice sopra è necessario aggiungere il file gen_validatorv31.js


0

Combinando tutti gli approcci possiamo fare qualcosa del genere:

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

Nota che se vuoi veramente controllare i valori dovresti farlo sul server, ma questo è fuori dallo scopo di questa domanda.


0

Puoi scorrere ogni input dopo l'invio e controllare se è vuoto

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>


Ciao, quando fornisci una soluzione, sarebbe fantastico fornire un motivo per cui la tua soluzione risolve il problema che potrebbe aiutare i futuri lettori.
Ehsan Mahmud
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.