开发者

How can you force jQuery Validate to show errors inside the form elements, instead of outside?

开发者 https://www.devze.com 2023-02-21 06:37 出处:网络
Taking this basic example of jQuery Validate (see link below), how can you instruct it to show the error messag开发者_运维技巧es inside the form elements, where possible (obviously checkboxes wouldn\'

Taking this basic example of jQuery Validate (see link below), how can you instruct it to show the error messag开发者_运维技巧es inside the form elements, where possible (obviously checkboxes wouldn't work)?

http://docs.jquery.com/Plugins/validation#source


Obviously you'll want to tailor it for your own form, but absolute positioning may help you here. For the example you cited:

[Truncated] markup:

<form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
   <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
   </p>
 </fieldset>
</form>

CSS:

.cmxform p{position:relative;}
.cmxform label.error{position:absolute; left: 11.7em; top:5px; display:block; width:180px; /*Computed width of text input was 189px*/ overflow:hidden;}

Of course, this approach does have one major drawback, and that is that the error label will hang above (and over) what the user is typing. On the jquery.com example, I had a red "Please enter at least 2 characters" message over the first letter of my name as I was typing. To remedy this, you'd want to do something like this:

$(document).ready(function(){
  $('.cmxform input[type=text]').focus(function(){
    $(this).siblings('.error').hide(); // Hide the error while the user is typing
  }).blur(function(){
    if( !$('#commentForm').validate().element(this) ){ // Re-validate this element, show the label if still invalid
      $(this).siblings('.error').show();
    }
  });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号