Dương Quang Thọ Dương Quang Thọ - 1 year ago 92
jQuery Question

How to create error messages validate form input with jQuery?

I have the register form as below:

<div class="form">
<form class="register-form" name="register-form">
<ul class="errorMessages"></ul>
<div class="user-name">
<input class="wrap" name="firstname" type="text" placeholder="firstname" required/>
<input class="wrap" name="lastname" type="text" placeholder="lastname" required/>
<input name="password" type="password" placeholder="password" autocomplete="off" required/>
<input name="email" type="text" placeholder="email address" autocomplete="off" required/>
button class="btn-signup" type="submit">Create</button>
<p class="message">Already registered? <a href="#">Sign In</a></p>

I create JQuery code check if input is blank, this will create error message"

$(function() {
var createAllErrors = function () {
var form = $(".register-form");
var errorList = $('ul.errorMessages', form);

var showAllErrorMessages = function () {

form.find(':invalid').each(function (index, node) {
var label = $('input').attr('name');
var message = node.validationMessage || 'Invalid value.';
.append('<li><span>' + label + ': ' + '</span>' + message + '</li>');
$('input[type=submit], button', form).on('click', showAllErrorMessages);

But when I press button I have result:

enter image description here

Any problem about label variable? or on form find invalid input?

Answer Source

The error is inside your each loop. You're never using the current index, and instead you requery the whole dom in search for input elements. Whenn you call getter functions on a jQuery collection, jQuery will return the attribute of the first element inside the collection. In your case this is the firstname input element. Use the current element of the each loop instead:

form.find(':invalid').each(function (index, node) {

  // WRONG: This will always return firstname
  //var label = $('input').attr('name');

  // RIGHT: Access the current element inside each loop
  var label = $(node).attr('name');

  // ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download