How to prevent submitting an empty form?

5

I have a custom search form for Google Search, and I want that, if the search field is empty, submit does not happen.

Can you block this via JavaScript?

    
asked by anonymous 04.11.2014 / 16:03

6 answers

10

You can do it via JavaScript

$("#form").submit(function() {
    if($("#campo").val()== null || $("#campo").val() ==""){
        alert('campo vazio');      
        return false;
    }
});

Or you can use HTML5

<input name="campo" id="campo" required/>
    
04.11.2014 / 16:44
4

Another way [which I personally find quite simple and complete] via JS is instead of using submit , using button with a salvar() function. In the function we create the business rules and if all conditions are true, just use the line of code

document.form.submit();
    
04.11.2014 / 17:45
3

You can use the require HTML 5 command:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
<form>
  <h1> Formulário Simples </h1>
  <div>
  <input type="text" id="txtNome" placeholder="Digite seu nome" required="required"/><span class="required">*</span>
    </div>
  <div>
  <input type="idade" id="txtIdade" placeholder="Digite sua idade" required="required"/><span class="required">*</span>
    </div>
  <button type="submit" class="btn btn-primary">
  <span>Enviar</span>
  </button>
</form>
  </div>
    
04.11.2014 / 17:12
3
<script>
  $(document).ready(function(){
      $(".form").submit(function(e) {
         e.preventDefault();//evito o submit do form ao apetar o enter..
      });
 });
</script>

And I would still use the logic suggested by PauloDias in a function where I would call it in the onclick and keyUp events

    
05.11.2014 / 00:11
1

Use the HTML5 required with fallback attribute for browsers (or versions) that do not support this attribute, which represent 30% of global users and 15% of users in Brazil, currently 2014), according to the Can I Use website - A considerable slice.

Next code: (Please, disregard the bad Practices of User Experience (UX) and HTML structure.)

if ($("<input />").prop("required") === undefined) {
  $(document).on("submit", function(e) {
    $(this)
      .find("input, select, textarea")
      .filter("[required]")
      .filter(function() { return this.value == ''; })
      .each(function() {
        e.preventDefault();
        $(this).css({ "border": "2px solid red" })
        alert($(this).prev('label').html() + " é obrigatório.");
      });
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><formaction="#">
    <label for="nome">Nome:</label>
    <input type="text" id="nome" required /><br>
    <label for="nome">E-mail:</label>
    <input type="text" id="email" required /><br>
    <input type="submit" />
</form>
    
13.11.2014 / 05:34
1

I suggest that you always add the Script below in the script in the project, so that all text fields that have the required tag will be validated if you have the empty field and / or have only spaces.

 $(document).ready(function(){
 
/**REQUIRED**/
$("input[required]").each(function(index) {
/** Utiliza por padrão o placeholder caso não encontre, utiliza o texto do label **/
var field = $(this).attr("placeholder") != null ? $(this).attr("placeholder") : $(this).parent().find("label").text();
$(this).rules("add", {
	required : function(element) {
		if(!$(element).val().trim()) {
			$(element).val("");
			return true;
			}
		return false;
     },
	messages : {required : "Campo é de preenchimento obrigatório."}
	});
});

 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
19.04.2016 / 15:12