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

I had a Jquery form that I was generating with an Ajax call. The user selected a state, then I retrieved the licenses for the agency that they selected from the state. I also defaulted to the first agency and ran a query. The problem was when the state had no agencies, it still ran the query. I wanted to know if I actually had an agency selected. Here is the answer using Jquery:

if ($('#myElement').length > 0) {
    ....
}

July 3rd, 2012

Posted In: javascript, JQuery

Leave a 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

This is a typical Jquery ajax request.

$.get(this.action, $(this).serialize(), function (data) {
    $('#expungeResult').html(data);
})

This works great until you realize that it is really taking data from a form and is changing data on the site. It should be a post, but it was mistakenly made with a get. The controller method was defined as POST only. This causes the an error in the server log.

Request method ‘GET’ not supported

Jquery $.get and $.post do support chaining .success(), .error() and .complete() methods. Unfortunately, they don’t have parameters.

$.ajax has what you need, at the expense of a more verbose declaration.

$.ajax({
    cache: false,
    type: "GET",
    url: this.action,
    data:$(this).serialize(),
    success: function (data) {
        $('#expungeResult').html(data)
    },
    error: function (jqXHR, textStatus, errorThrown) {
        $('#expungeResult').html(textStatus).append("...").append(errorThrown).css('color', 'red')
    }}
);

Now, “error…Request method ‘GET’ not supported” is displayed in red in my display area. An ugly message, but at least the user will not keep clicking the button because it looks like nothing happened.

June 12th, 2012

Posted In: javascript, JQuery

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

I was working on a problem where I needed to change the text in a menu to be the name of the department, then the phone number to the department. Both of which had to be a link to the department’s page. I figured that this would be very easy in JQuery. It took a bit of time, but I figured out a fairly easy solution. I figured out a few things along the way.

  • fadeIn, fadeOut, fadeTo only change opacity
  • calling .html on an item that was faded-out immediately makes it visible

The final solution involved making an array that held the two sets of html for the menu item. I incremented a counter and modded by the number of items in the array to get the next one to display. Then I faded out the anchor tag within the item, changed the html of the now faded anchor to some html that was set to display:none, then faded in the anchor within the list item. I surrounded that with a set interval.

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var menuText = ['<a href="/...." style="display:none;" title="My Title">Department Name</a></li>',   // first menu item html
                            '<a href="/...." style="display:none;" title="My Title">Phone Number</a></li>'];     // second menu item html
            var menuItem = 0;

            setInterval(function() {
                menuItem = ++menuItem % 2;  // 0 or 1

                $("#myTarget a").fadeOut(1000);  // 1 second
                $("#myTarget").html(menuText[menuItem]);  // change the html to be new html that is set to hidden
                $("#myTarget a").fadeIn(1000);   // 1 second
            }, 4 * 1000);  // 4 seconds - ensure that this is longer than the fade out/in duration
        });
    </script>
</head>
<body>
    <ul>
        <li>list item 1</li>
        <li>list item 2</li>
        <li>list item 3</li>
        <li id="myTarget"><a href="/...." title="My Title">Department Name</a></li>  // start with the initial value
        <li>list item 4</li>
        <li>list item 5</li>
    </ul>
</body>
</html> 

March 7th, 2011

Posted In: JQuery

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

Next Page »
LinkedIn Auto Publish Powered By : XYZScripts.com