1

Utilizo o JQuery Validate para fazer a validação de inputs, porém quando a validação falha, é criado um label de mensagem de erro ao lado do input.

Meu objetivo é fazer com que esse label seja mostrado abaixo do input, sem alterar a posição dos inputs ao lado do input validado, mas quando utilizo a propriedade CSS 'display: block', os inputs ao lado são empurrados para baixo, como se houvesse um '< br >' entre os inputs e o label de erro gerado pela validação.

Segue demonstração

Antes da validação: Antes Depois da validação: inserir a descrição da imagem aqui

O código CSS do label de erro é muito simples:

label.error {
font: 11px arial;
margin-left: 2px;
display: block; }

Caso minha pergunta esteja incompleta, por favor me avise que irei complementar a pergunta o mais rápido possível.

3
  • Como aparecia antes de vc colocar display block? Por cima dos outros inputs ao lado?
    – Meu ovo
    8/01/2018 às 17:51
  • Pode postar o HTML só dessa parte desses 3 campos?
    – Meu ovo
    8/01/2018 às 18:07
  • Vc tentou com display:inline-block?
    – hugocsl
    8/01/2018 às 18:11

1 Resposta 1

1

Você pode converter esse label para position: absolute e posicioná-lo abaixo do input. No entanto é preciso que o elemento onde a label é criada tenha position: relative. Inclua no CSS o código abaixo para setar todos os elementos com position: relative:

*{
   position: relative;
}

É importante também que cada input esteja separado um do outro dentro de um elemento (uma div ou label, por exemplo):

<form>
    <div>
        E-mail <input ...>
    </div>
    <div>
        Telefone <input ...>
    </div>
    <div>
        Telefone adicional <input ...>
    </div>
</form>

E o CSS abaixo irá posicionar a label:

label.error{
   position: absolute;
   left: 0;
   top: 23px;
   margin-left: 0;
}

*{
   position: relative;
}

Veja como fica:

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
	<script>
	$.validator.setDefaults({
		submitHandler: function() {
			alert("submitted!");
		}
	});

	$().ready(function() {
		// validate the comment form when it is submitted
		$("#commentForm").validate();

		// validate signup form on keyup and submit
		$("#signupForm").validate({
			rules: {
				firstname: "required",
				lastname: "required",
				username: {
					required: true,
					minlength: 2
				},
				password: {
					required: true,
					minlength: 5
				},
				confirm_password: {
					required: true,
					minlength: 5,
					equalTo: "#password"
				},
				email: {
					required: true,
					email: true
				},
				topic: {
					required: "#newsletter:checked",
					minlength: 2
				},
				agree: "required"
			},
			messages: {
				firstname: "Please enter your firstname",
				lastname: "Please enter your lastname",
				username: {
					required: "Please enter a username",
					minlength: "Your username must consist of at least 2 characters"
				},
				password: {
					required: "Please provide a password",
					minlength: "Your password must be at least 5 characters long"
				},
				confirm_password: {
					required: "Please provide a password",
					minlength: "Your password must be at least 5 characters long",
					equalTo: "Please enter the same password as above"
				},
				email: "Please enter a valid email address",
				agree: "Please accept our policy",
				topic: "Please select at least 2 topics"
			}
		});

		// propose username by combining first- and lastname
		$("#username").focus(function() {
			var firstname = $("#firstname").val();
			var lastname = $("#lastname").val();
			if (firstname && lastname && !this.value) {
				this.value = firstname + "." + lastname;
			}
		});

		//code to hide topic selection, disable for demo
		var newsletter = $("#newsletter");
		// newsletter topics are optional, hide at first
		var inital = newsletter.is(":checked");
		var topics = $("#newsletter_topics")[inital ? "removeClass" : "addClass"]("gray");
		var topicInputs = topics.find("input").attr("disabled", !inital);
		// show when newsletter is checked
		newsletter.click(function() {
			topics[this.checked ? "removeClass" : "addClass"]("gray");
			topicInputs.attr("disabled", !this.checked);
		});
	});
	</script>
	<style>
	#commentForm {
		width: 500px;
	}
	#commentForm label {
		width: 250px;
	}
	#commentForm label.error, #commentForm input.submit {
		margin-left: 253px;
	}
	#signupForm {
		width: 670px;
	}
	#signupForm label.error {
		margin-left: 10px;
		width: auto;
		display: inline;
	}
	#newsletter_topics label.error {
		display: none;
		margin-left: 103px;
	}
   
   form div{
      display: inline-block;
   }
   
   .submit{
      margin-top: 20px;
   }

label.error{
   position: absolute;
   left: 0;
   top: 23px;
   margin-left: 0;
}

*{
   position: relative;
}

	</style>
</head>
<body>
<div id="main">

	<form class="cmxform" id="signupForm" method="get" action="" style="width: 1000px; display: block;">
		<fieldset>
			<div>
				<label for="firstname">Firstname</label>
				<input id="firstname" name="firstname" type="text">
			</div>
			<div>
				<label for="lastname">Lastname</label>
				<input id="lastname" name="lastname" type="text">
			</div>
			<div>
				<label for="username">Username</label>
				<input id="username" name="username" type="text">
			</div>
			<p>
				<input class="submit" type="submit" value="Submit">
			</p>
		</fieldset>
	</form>
</div>

1
  • Funcionou perfeitamente, muito obrigado pelo suporte! 9/01/2018 às 12:42

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .