Himanshu Sharma Himanshu Sharma - 5 months ago 8
jQuery Question

How to give custom location to error in jQuery Validation

I want to place an error for

logemail
in
#logemailerror
and error for
logpass
in
#logpasserror
.



$('document').ready(function() {
/* validation */
$("#login-form").validate({
rules: {
password: {
required: true,
},
user_email: {
required: true,
email: true
},
},
messages: {
password: {
required: "please enter your password"
},
user_email: "please enter your email address",
},
submitHandler: submitForm
});

<div id="login_form" style='display:none'>
<div class="modal-dialog" style="max-width:400px; text-align:center;">
<div class="modal-content login-modal">
<div class="modal-header login-modal-header">
<button type="button" class="close"><span aria-hidden="true">&times;</span>
</button>
<h4 class="modal-title text-center" id="loginModalLabel">Log-In</h4>
</div>
<div class="modal-body">
<div class="text-center">
<form id="login" action="javascript:alert('success!');">
<input type="hidden" name="action" value="user_login">

<input type="hidden" name="module">
<div id="error">
<!-- error will be shown here ! -->
</div>
<div class="form-group" style="margin-left:8%;">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-user"></i>
</div>
<input type="text" name="logemail" class="form-control" placeholder="E-Mail">
</div>
<div id="logemailerror"></div>
</div>
<div class="form-group" style="margin-left:8%;">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-lock"></i>
</div>
<input type="password" name="logpass" class="form-control" placeholder="Password">
<br />
</div>
<div id="logpasserror"></div>
</div>
<input value="Login" name="Login" id="submit" class="btn bt-login" type="submit" style="margin-left:8%; width:92%" />
<div class="clearfix"></div>
<div class="login-modal-footer">
<div class="row">
<div class="col-xs-8 col-sm-8 col-md-8">
<i class="fa fa-lock"></i>
<a href="#" id="forget_tab" class="forgetpass-tab"> Forgot password? </a>
</div>

<div class="col-xs-4 col-sm-4 col-md-4">
<i class="fa fa-check"></i>
<a href="#" id="signup_tab" class="signup-tab"> Sign-Up </a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>





Please help me. How could this be achieved? Whenever I try to use
errorplacement
the javascript stops working.

Answer

look at the documentation for errorPlacement

$("#login-form").validate({
  rules: {
    password: {
      required: true,
    },
    user_email: {
      required: true,
      email: true
    }
  },
  messages: {
    password: {
      required: "please enter your password"
    },
    user_email: "please enter your email address",
  },
  submitHandler: submitForm,

  errorPlacement: function(error, element) {
    if (element.attr("name") == "logemail") {
      $("#logemailerror").append(error);
    } else if (element.attr("name") == "logpass") {
      $("#logpasserror").append(error);
    }
  }

});