Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

In a previous post, I showed how to declare an error label container for jquery validation messages. http://javaninja.net/2010/12/change-where-jquery-validation-messages-are-displayed/.

Today, we had a problem where the markup of the page required us to need to specify for this particular field, display the messages here. The default behavior of showing the messages by the fields was still desired, but the mark-up was preventing this. Checker was being added by Jquery Uniform dynamically. It was restricted to width=”25″ and height=”25″ to force the checkbox to a certain size. The problem is that the regular Jquery Validation error messages defaults to placing the error message after the target element. Unfortunately, this places it within the div that is limiting its size.

<div class="x2-top row">
    <div class="col-md-9  uniformed">
        <div id="acceptedTermsDiv checker">
            <input type="checkbox" 
                   name="acceptedTerms" 
                   id="acceptedTerms" 
                   style="width:20px;" 
                   value="true" 
                   tabindex="6"/>
            <span class="tooltip_text" 
                  data-toggle="tooltip" 
                  data-placement="bottom" 
                  title="You must accept the Terms and Conditions." 
                  data-container="#acceptedTermsDiv">
                <label for="acceptedTerms">I Accept The <a href="#" class="inline" id="termsLink">Terms &amp; Conditions</a></label>
            </span>                                                                                   
        </div>
    </div>
</div>

One way to solve this is to use a custom errorPlacement to force the messages to a custom location.

<div class="x2-top row">
    <div class="col-md-9  uniformed">
        <div id="acceptedTermsDiv checker">
            <input type="checkbox" 
                   name="acceptedTerms" 
                   id="acceptedTerms" 
                   style="width:20px;" 
                   value="true" 
                   tabindex="6"/>
            <span class="tooltip_text" 
                  data-toggle="tooltip" 
                  data-placement="bottom" 
                  title="You must accept the Terms and Conditions." 
                  data-container="#acceptedTermsDiv">
                <label for="acceptedTerms">I Accept The <a href="#" class="inline" id="termsLink">Terms &amp; Conditions</a></label>
            </span>                                                                                   
        </div>
    </div>
</div>

The custom errorPlacement will look like this:

errorPlacement: function(error, element) {
    if (element.attr("type") == "checkbox") {
        error.insertAfter($(element).closest(".checker").closest('div'));
    } else {
        error.insertAfter(element);
    }
}

June 17th, 2015

Posted In: java ninja, Javaninja, javascript, JQuery

Tags: , , , , , , ,

Leave a Comment

The previous article regex validation with jquery validation plugin laid the foundation for creating custom validation methods.

One thing I ran into was the case where multiple validations were created for a password, but they only test for the existence of one character that matches the regex. Meaning, does the password contain a lower-case letter? The advantage of using multiple validations, is that the user can be told which types of characters they need to make their password validate correctly.

I needed to validate that a password contains at least one lower-case letter, at least one upper-case letter, at least one number, and at least one symbol. First, I created the custom validations.


/**
 * Custom validator for contains at least one lower-case letter
 */
$.validator.addMethod("atLeastOneLowercaseLetter", function (value, element) {
    return this.optional(element) || /[a-z]+/.test(value);
}, "Must have at least one lowercase letter");

/**
 * Custom validator for contains at least one upper-case letter.
 */
$.validator.addMethod("atLeastOneUppercaseLetter", function (value, element) {
    return this.optional(element) || /[A-Z]+/.test(value);
}, "Must have at least one uppercase letter");

/**
 * Custom validator for contains at least one number.
 */
$.validator.addMethod("atLeastOneNumber", function (value, element) {
    return this.optional(element) || /[0-9]+/.test(value);
}, "Must have at least one number");

/**
 * Custom validator for contains at least one symbol.
 */
$.validator.addMethod("atLeastOneSymbol", function (value, element) {
    return this.optional(element) || /[!@#$%^&*()]+/.test(value);
}, "Must have at least one symbol");

Once the validators were created, now it was time to use them.

<script>
    $(function () {
        $("#change-password").validate({
            rules: {
                password: {
                    required: true,
                    atLeastOneLowercaseLetter: true,
                    atLeastOneUppercaseLetter: true,
                    atLeastOneNumber: true,
                    atLeastOneSymbol: true,
                    minlength: 8,
                    maxlength: 40
                }
            }
        });
    });
</script>

An alternative way to specify the rules is

$("#password").rules("add", {
    required: true,
    minlength: 8,
    maxlength:40,
    atLeastOneLowercaseLetter: true,
    atLeastOneUppercaseLetter: true,
    atLeastOneNumber: true,
    atLeastOneSymbol: true
});

June 13th, 2015

Posted In: java ninja, Javaninja, javascript, JQuery

Tags: , , , ,

Leave a Comment

We needed several Jquery validations with regexes. I coded various custom validators with the regex included, so the regex could be re-used instead of typing the regex again and again.

        /**
         * Custom validator for letters (uppercase/lowercase)
         */
        $.validator.addMethod("lettersOnly", function (value, element) {
            return this.optional(element) || /^[a-zA-Z]+$/i.test(value);
        }, "Please enter letters only.");

        /**
         * Custom validator for numbers only (0-9)
         */
        $.validator.addMethod("numbersOnly", function (value, element) {
            return this.optional(element) || /^[0-9]+$/i.test(value);
        }, "Please enter numbers only.");

        /**
         * Custom validator for dates (0-9 and slashes).  Does not check month, day or year.
         */
        $.validator.addMethod("date", function (value, element) {
            return this.optional(element) || /^[0-9/]+$/i.test(value);
        }, "Please enter dates only.");

        /**
         * Custom validator for phone numbers (0-9, (, ) and -).  Does not check number of digits, etc.
         */
        $.validator.addMethod("phone", function (value, element) {
            return this.optional(element) || /^[0-9()-]+$/i.test(value);
        }, "Please enter dates only.");

        /**
         * Custom validators for letters and numbers only.  Uppercase/lowercase letters and numbers (0-9).
         */
        $.validator.addMethod("lettersAndNumbersOnly", function (value, element) {
            return this.optional(element) || /^[a-zA-Z0-9]+$/i.test(value);
        }, "Please enter letters and numbers only.");

Here is an example of how the validation was wired in via the rules section of the Jquery validation plugin

            rules: {
                firstName: {
                    required: true,
                    minlength: 1,
                    maxlength: 32,
                    lettersOnly: true
                },

April 1st, 2014

Posted In: javascript, JQuery

Tags: , , ,

One Comment

It has been a while since I wrote a form. I kept posting data even though the Jquery Validation fired and was not valid. I forgot that you have to check for a valid form. I also learned that you can also add a submit handler to the validation call. Here is what the completed validation and ajax call looked like. Notice that in this form, I disable the submit button belonging to the form just before the ajax request is sent.

$(document).ready(function () {
    $("#expungementForm").validate({
        submitHandler: function(form) {
            $.ajax({
                cache: false,
                type: "POST",
                url: form.action,
                data: $(form).serialize(),
                beforeSend: function (jqXHR, settings) {
                    $('input[type="submit"]', form).attr('disabled', true);
                },
                success: function (data) {
                    $('#expungeResult').html(data)
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('#expungeResult').html(textStatus).append("...").append(errorThrown).css('color', 'red')
                }});
            return false;
        }
    });
});

June 13th, 2012

Posted In: HTML, javascript, JQuery, json

Tags: , , , , ,

Leave a Comment

IE8 displaying Jquery dialog with scroll bars

This was happening only on IE8 (native and CoRD). It was working correctly on Chrome and Firefox.

The solution is to call .height(‘auto’) after the dialog is created.

                    $(document).ready(function() {
                        $('#phoneDataButton').click(function() {
                            $('#phoneDataSearchForm').dialog({
                                modal:true,
                                width: 700,
                                close: function() {
                                    $('#phoneSearchResults').html("");
                                    location.reload(true);
                                }
                            }).height('auto')
                        })
                    })

October 7th, 2011

Posted In: javascript, JQuery

Tags: , ,

Leave a Comment

Yeah. jQuery form validation is proving to be very nice. If you have been following this blog, you have seen how to set-up the standard validations and even create your own custom validation. One problem I had to solve was that the validation message broke my UI. I still needed the message, but I didn’t need it to display in the default location which is to the right of the field. That turn out to be very easy. First define an area where you want your validation messages to be displayed.

<form name="myForm" id="myForm" action="">
     <div id="myErrorLabelContainer"></div>
     <input class="required date dateRange" type="text" id="myField" name="myField">
</form>
<input type="submit" value="Go Validate"/>

The next step is to tell the jQuery Validation plugin that you want to use this for the error messages. This is accomplished with the errorLabelContainer option.

<script type="text/javascript">
    $(document).ready(function() {
        $('#executiveConsoleForm').validate({
            errorLabelContainer: "#myErrorLabelContainer"
        });
    });
</script>

This is just the beginning of error place. There is also the errorPlacement option that can be used to define logic to indicate where you want error messages to be displayed. A smal example of this can be found in the groups documentation

December 15th, 2010

Posted In: javascript, JQuery

Tags: , , ,

One Comment

My previous blog entry showed how to quickly add Jquery Validation. One that was not there was the ability to compare two fields that contain dates and validate that the field that should hold the older date was in-fact older. Here is how I created the custom validation.

First I defined the custom validation called dateRange and it’s error message. This allows me to dateRange as a CSS class name for validation purposes.

<script type="text/javascript">
     $(document).ready(function() {
        $.validator.addMethod("dateRange", function() {
            return new Date($("#olderDate").val()) < new Date($("#newerDate").val());
        }, "Please specify a correct date range<br/>The older date must be before the newer date.");

Then I set-up the form for validation. I added the groups option so that the plugin knows that the fields should be validated together. Without this validation, each field will be validated and if the validation failed, both fields would have error messages.

          $('#myForm').validate({
            groups: {
                dateRange: "olderDate newerDate"
            });
    });
</script>

All that is left is the HTML of the actual form. Here I create a form that has two input fields. I indicate that both fields are required, they must be dates and they should be in the correct chronological order.

<form name="myForm" id="myForm" action="">
     <input class="required date dateRange" type="text" id="olderDate" name="olderDate">
     <input class="required date dateRange" type="text" id="newerDate" name="newerDate">
     <input type="submit" value="Let's date validate"/>
</form>

December 15th, 2010

Posted In: javascript, JQuery

Tags: , , ,

One Comment

$('.detail').click( function() {
       $dialog.dialog({title:$(this).attr('title')});
       $dialog.html('<div class="loading-center" />');
       $dialog.dialog('open');    
       $.get( $(this).attr('href'), function(data) {
           $dialog.html(data);
       });
       return false;
   });
<a class="detail" title="Smith, Tara (BHE)" href="/intranet-templating/employeedir/employeedetails.do?userId=221014">Smith, Tara (BHE)</a>

class=”detail” is how the links are selected

November 29th, 2010

Posted In: JQuery

Tags: , , , ,

Leave a Comment

WP to LinkedIn Auto Publish Powered By : XYZScripts.com