How can you make jQuery Validate show errors inside form elements, not outside?

Taking this basic jQuery Validate example (see link below), how can you instruct it to display error messages inside form elements where possible (obviously, the checkboxes don't work)?

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

+4
source share
1 answer

Obviously, you will want to adapt it to your own form, but absolute positioning can help you here. For the example you specified:

[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 has one major drawback, and this means that the error label will hang over (and over) what the user enters. Using jquery.com as an example, I had a red message "Please enter at least 2 characters" above the first letter of my name when I typed. To fix this, you would like 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(); } }); }); 
+2
source

Source: https://habr.com/ru/post/1346356/


All Articles