Search code examples
javascriptjqueryjquery-validateerrorplacement

Using jquery validate errorPlacement to get error message in a specific div


I am attempting to use jQuery Validate's errorPlacement function to place an error message, but I cannot figure it out. Whenever I hit submit, the input slides down, instead of the error placing in the newsletterValidate div.

Does anyone see what I am doing wrong in my errorPlacement code?

enter image description here

$('#newsletterForm').validate({
		//errorClass: 'invalid',
		errorPlacement: function(error, element) { 
			//element.val(error[0].outerText);
			//error.appendTo(element.next('div'));
			 error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
		},
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			email: {
				required: "Please enter your email address",
				email: "Please enter a valid email address"
			}
		},
		submitHandler: function(form) {
			event.preventDefault();
			var datastring = $('#newsletterForm').serialize();
			$.ajax({
				url: 'http://localhost:8080/php/newsletterSend.php',
				type: 'POST',
				data: datastring
				,
				success: function(data) {
					console.log(data);
					if (data == 'Error!') {
						alert('Unable to submit form!');
						alert(data);
					} else {
						$('#newsletterInput')[0].reset();
						$('#newsletterSuccess').show();
					}
				},
				error: function(xhr, textStatus, errorThrown) {
					alert(textStatus + '|' + errorThrown);
					console.log('error');
				}
			});
		}
	});
#newsletterInput {
	width: 70%;
	border: none;
	padding: 15px 10px;
	outline: none;
	font-size: 1.1rem;
	font-family: 'Nunito', sans-serif;
	display: inline-block;
  background: pink;
}
#newsletterSubmit {
	width: 25%;
	display: inline-block;
	border: none;
	font-size: 1.1rem;
	font-family: 'Nunito', sans-serif;
	padding: 15px 10px;
	cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<div>
  <form id="newsletterForm">
    <input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
  </form>
</div>
<div id="newsletterValidate"></div>


Solution

  • error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
    

    I'm not sure why you are using jQuery to traverse around inside the DOM when you already know the unique id. So just skip right to your target...

    error.appendTo($('#newsletterValidate'));
    

    Demo 1: jsfiddle.net/b2enbs0s/

    However, now that it's working, you can see there's a different problem. The message is being repeated.

    That's because you're trying to place the message outside of the form container...

    <div>
        <form id="newsletterForm">
            <input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
        </form>
    </div>
    <!--// outside of the form //-->
    <div id="newsletterValidate"></div>
    

    In this case, the plugin creates the validation message but cannot find it again in order to properly toggle it.

    The fix is to place the message element inside of the form container where the plugin can automatically find & toggle after it's created. The following structure visually renders identical to your original layout...

    <form id="newsletterForm">
        <div>
             <input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
        </div>
        <!--// inside of the form //-->
        <div id="newsletterValidate"></div>
    </form>
    

    Final Working Demo: jsfiddle.net/b2enbs0s/1/