Click here to Skip to main content
Click here to Skip to main content

jQuery Validation Styles

By , 24 Jun 2012
 

Introduction 

This application makes simple client side form validation with the help of jQuery plugins. Here I would like to show different validation style of jQuery with basic sample of HTML and jQuery.


I have published article at http://saffroze.com/jquery-validation-styles/

Background  

ASP.NET MVC 3 uses jQuery validation for form validations and jQuery validation library has a remote validation feature, using this feature by ASP.NET MVC libraries is really easy you can find more about it http://docs.jquery.com/Plugins/validation.

  • Every validation attribute has a ToJson method which serializes attributes into a dictionary
    $("#form").validate({
     
    rules: {
     
    firstname: { required: true, minlength: 5, maxlength: 10 },
     
    lastname: { required: true, minlength: 5, maxlength: 10 },
     
    email: { required: true, email: true },
     
    mobile: { required: true, digits: true, minlength: 10, maxlength: 10 }
     
    }
     
    });
  • All error labels are displayed inside an unordered list with the ID “validationSummary” Additonal container for error messages. The elements given as the “errorContainer” are all shown and hidden when errors occur.
    errorContainer: "#validationSummary"
  • The error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list.
    errorLabelContainer: "#validationSummary ul"
  • Therefore the error labels are also wrapped into li elements (wrapper option).
    wrapper: “li”
  • A custom message display handler. Gets the map of errors as the first argument and and array of errors as the second, called in the context of the validator object.
    showErrors: function (errorMap, errorList) {
    .
    .
    .
    } 

Implementation 

    This code demonstrates a basic jQuery validation sample, jQuery Validate plugins validates the form before it submitted, if form is valid it submits the form, otherwise form doesn’t get submitted.

  1. Include jQuery Plugin and Validations scripts into your page.

    <script type="text/javascript" src="../../Scripts/jquery.validate.js">&lt;/script>
    
        &lt;script type="text/javascript" src="../../Scripts/jquery-ui-1.8.11.js">&lt;/script> 
  2. Add following script in your page. It is very descriptive so no need to explain each and every lines.
        $(document).ready(function () {
            //Set border color when text class getting focus or remove border color when lost focus from textbox.
            $('.text')
            .focus(function () { $('.text').removeClass('focused'); $(this).addClass('focused'); })
            .blur(function () { $(this).removeClass('focused'); });
     
            //Fire validation events
            $("#form").validate({
     
                //Setting validation type like, Required, Minimum or Maximum Length, Data Type etc.
                rules: {
                    firstname: { required: true, minlength: 5, maxlength: 10 },
                    lastname: { required: true, minlength: 5, maxlength: 10 },
                    email: { required: true, email: true },
                    mobile: { required: true, digits: true, minlength: 10, maxlength: 10 }
                },
     
                //All error labels are displayed inside an unordered list with the ID "validationSummary"
                //Additonal container for error messages. The elements given as the "errorContainer" are all shown and hidden when errors occur.
                errorContainer: "#validationSummary",
     
                //But the error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list.
                errorLabelContainer: "#validationSummary ul",
     
                //Therefore the error labels are also wrapped into li elements (wrapper option).
                wrapper: "li",
     
                //A custom message display handler. Gets the map of errors as the first argument and and array of errors as the second, 
                //called in the context of the validator object.
                showErrors: function (errorMap, errorList) {
                    $('.errorList').hide();
                    $('.inlineMessage').hide();
                    $('#validationSummary').hide();
                    var messages = "";
                    $.each(errorList, function (index, value) {
                        var id = $(value.element).attr('id');
                        messages += "<span>" + (index + 1) + ". <a title='click to view field' href='javascript:setFocus(" + id + ");'>[" + $(value.element).attr('name') + "]</a> " + value.message + "</span>
    ";
                    });
                    messages = "
     
     
    <div class='errorWrapper'>
     
     
    <h1>Please correct following errors:</h1>
     
    " + messages + "</div>
     
    ";
                    switch ($('input[name=DisplayType]:checked', '#form').val()) {
                        case "Popup":
     
                            //Showing validation summary in Popup window
                            $('#dialog-validation').html(messages);
                            $('#dialog-validation').dialog('open');
                            break;
                        case "Summary List":
     
                            //Showing validation summary in list of the same page
                            $('#summary-validation').html(messages);
                            $('#summary-validation').show("fast");
                            break;
                        case "Inline":
     
                            //Showing validation in inline format
                            $.each(errorList, function (index, item) {
                                $(item.element).next('div').html("<span style='font-weight:bold'>[" + $(item.element).attr('name') + "]</span> " + item.message);
                                $(item.element).next('div').show("fast");
                            });
                            break;
                    }
                },
     
                //If all validations are successfully validate then execute submitHandler function
                submitHandler: function () {
                    $('#summary-validation').empty();
                    $('#dialog-validation').empty();
                    alert("All fields are valid!")
                }
            })
     
            //jQuery Modal Dialog boxes can also use to display list of validation erorrs.
            $("#dialog-validation").dialog({
                resizable: false,
                height: 190,
                width: 350,
                modal: true,
                autoOpen: false,
                title: "Validation Errors",
                buttons: {
                    "Ok": function () {
                        $(this).dialog("close");
                        $('.focused').focus();
                    }
                }
            });
        });
     
        //If validation errors are occured in any field, it will display field name with link, clicking on link it will set focus of perticular field.
        function setFocus(ele) {
            $(ele).focus();
        }
    
  3. HTML page:
    1.  If you need show validation near to field then it should be compulsory to add “” with class name is “inlineMessage”.
      <div class="formWrapper" id="formStyle"><form id="form" action="" method="post" name="form"><label>First Name</label> <input id="firstname" class="text" type="text" name="firstname" />
      <div class="inlineMessage"></div> </form>
      </div>
    2. Hidden container for Error Messages
      <div id="validationSummary">
             	<ul class="errorMessageList">
      	       </ul>
          	</div>
      
    3. Display Validation Summary in same page
      <div style="display: none;" id="summary-validation" class="errorList">
      	    </div>
      
    4. Display Validation Summary in Modal Dialog box.
      <div style="display: none;" id="dialog-validation" class="errorList">
        </div>
      
    5. Add Style for Form, Inputbox, Button, Dialog and Validation Messages.Please visit Views/Shared/_Layout.cshtml

Your Thoughts

If you find some issues or bugs with it, just leave a comment or drop me an email. If you make any notes on this, let me know that too so I don’t have to redo any of your hard work. Please provide a “Vote” if this would be helpful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sunasara Imdadhusen
Software Developer (Senior) Infostretch Ahmedabad-Gujarat
India India
Member
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.

sunaSaRa Imdadhusen
 
AWARDS:
  1. 1st Best Asp.Net article of SEP 2010
  2. 2nd Best Asp.Net article of MAY 2011
 
Read More Articles...

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhow to validate for duplicationmemberGorPedoC15 May '13 - 19:03 
Hi Pal,
 
im new to mvc and im trying to use jquery for an issue.My query is, like how to validate using jquery for duplication
 
my requirement in jquery is :
1. The numbers 1-5 alone should be accepted
2. Any duplication must be checked.
 
My code:
 
<pre lang="HTML"><script type="text/javascript">
      function validate(cid, cval) {
                  var origCnt = 5;
                  var boxes = $('input[name=ProcessNames]');
                  if (cval > origCnt) {
                        alert("This value greater than maximum no of attempt");
                        $('#Attemt').val('');
                  }
                  else if (cval = 'what should be given here') {
                        alert("Attempt No Already Exists for this Client");
                        $('#Attemt').val('');
                  }
            }
</script></pre>
 

Any suggestions please Dr,
 
Thank You
 
Rose | [Rose] GorPedoC Rose | [Rose]
 

AnswerRe: how to validate for duplicationprofessionalSunasara Imdadhusen15 May '13 - 19:17 
Not clear at all!!! Could you please explain in detail what exactly you want?

sunaSaRa Imdadhusen
+91 99095 44184

GeneralRe: how to validate for duplicationmemberGorPedoC20 May '13 - 1:02 
Hi
Thank you for replying my query, i hav made some changes in the query u hav thought and its working fine... Thumbs Up | :thumbsup:
 
Its a wonderful post Thumbs Up | :thumbsup: , thank u once again, it made my search simpler. Thumbs Up | :thumbsup:    Big Grin | :-D
QuestionjQuery Validation StylesmemberAshish Rathod2 Nov '12 - 19:08 
Thnaks Smile | :)
GeneralMy vote of 5memberOlivier Giulieri15 Oct '12 - 20:54 
Thank you for sharing. It's useful and easy to use.
GeneralRe: My vote of 5memberSunasara Imdadhusen15 Oct '12 - 21:22 
Thanks for your appreciations! you will get more articles here Web App Development Company Blog[^]

sunaSaRa Imdadhusen
+91 99095 44184

GeneralMy vote of 5memberUnareshraju14 Oct '12 - 19:11 
very good
GeneralRe: My vote of 5memberSunasara Imdadhusen15 Oct '12 - 21:20 
Thanks you very much

sunaSaRa Imdadhusen
+91 99095 44184

QuestionValidation OnBlur or onfocusout.... suggestionmemberenzorio25 Sep '12 - 5:32 
//How would I achieve validation when I focus out of the input fields (before clicking the validate button)?

 
//Outside-Before the  $(document).ready(
var v = new Object();
 

//Then set v Inside the $(document).ready(
var v = $('#form').validate(/*{...options...}*/);
 
//Before the rules property setting
// I added the onfocusout property
onfocusout: true //??? This does not do anything...???:confused:

// Before $("#dialog-validation").dialog(
$('#firstname').blur(function () {
	v.element('#firstname');
}); 
 
//Is this the way to go? I got some help here: 
//http://stackoverflow.com/questions/9189910/jquery-form-validation-onblur#answer-9197295

AnswerRe: Validation OnBlur or onfocusout.... suggestionmemberSunasara Imdadhusen15 Oct '12 - 21:19 
Thanks for your findings and appreciations!

sunaSaRa Imdadhusen
+91 99095 44184

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 25 Jun 2012
Article Copyright 2012 by Sunasara Imdadhusen
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid