How to prevent Submit from an empty form?

Asked

Viewed 41,250 times

8

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

You can do this blocking via Javascript?

6 answers

14

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

    Note: Internet Explorer 9 or older does not understand the required. However avoid unnecessary JS is always good.

  • In addition, it still does not have good acceptance in furniture.

5

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

document.form.submit();

3

<script>
  $(document).ready(function(){
      $(".form").submit(function(e) {
         e.preventDefault();//evito o submit do form ao apetar o enter..
      });
 });
</script>

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

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>
<script src="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>

  • detail, you put the required="required" of the first field in the old wrong place :)

  • Truth... Thank you.

1

I suggest that you always add the Script below in the script in the project, so that all fields of the type text that has 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>

1

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

Code to follow:
(Please disregard bad User Experience (UX) practices 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>
<form action="#">
    <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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.