JQuery Validate for 3 field date

A difficult and challenging task I had been given is to use the JQuery validate.js to validate the date fields, but this was then split out into 3 fields. One for day, month and of course year, which sounds easy, but it was not. The issue comes that validate.js is built to validate one field on its own and we wanted to validate not just each field, but also as a whole date.

I researched the web and most developers suggested amending the JavaScript library file. However the version we had was minified and of course we had other teams using that copy, so using this method would affect others code. I thought about putting the validation for the whole date in with each of the fields, but this then produced the same validation each message for the whole date 3 times because it was doing it for each of the fields. There was a suggestion from developer to use a group method, but I couldn’t seem to get that working.

So I persisted to make my own method. This may not be the best, but I found it worked well and passed testing so it can’t be that bad. You can read more about the library of JQuery Validate here and learn the basics, which will make this all seem a bit easier.

First we need to validate each field on their own for example make sure the month is between 1 and 12. Instead of making a validation made for each field I made a universal method that all of them could use.

In the example below you can see in the ‘params’ parameter I passed in a array that has the minimal number and the maximum number. You would pass for example of month [1,12]. This is then validated on exit to check the ‘value’ of the field, stored in ‘dateValue’, is between or equal to the range.

$.validator.addMethod("vailddatefield",

function (value, element, params) {

var dateValue = parseInt(value, 10);
var Min = parseInt(params[0], 10);
var Max = parseInt(params[1], 10);
return this.optional(element) || (dateValue >= Min && dateValue <= Max );

},"Please enter a valid age"

);

You can then attach this to the field like so:

//Month validation
$(".month").rules("add", {

vailddatefield: [1,12],
messages: {
vailddatefield:  'Please enter a month value between 1 and 12'
}

});

The issue then comes when you want to validate these all together. If you was to enter the validation for the whole date in the method above then when an error happened it would produce the message once for each field with the same text. This then means we need a single field to evaluate if the full date is valid and then validate against that.

If you add the below snippet into the previous method, you can then pass the class or IDs for each of the date fields. These can then be concatenated together to make a full date, then put into a hidden field. This now holds our full date string in good format ready for validating.

//validate full date
var day = $(params[2]);
var month = $(params[3]);
var year = $(params[4]);
var fullDate= $(params[5]);

$(fullDate).val($(day).val() + '/' + month.val() + '/' + year.val());

This however still doesn’t solve how we are going to validate it. To fire the validation by the library as normal, you need to give focus to the field then leave it, which is impossible because it is hidden. So we use some magic… If you put the below statement in, it forces the JavaScript to validate that field. This then runs its attached validation from the library. If you enter this into the previous method as well, so no matter which fields they start or finish in, it will validate the full date in the end. You will also only get only one message to appear if the field is invalid.

$(fullDate).valid()

Something I also did was stop it validating until all the fields are complete, as you don’t want to say their date is invalid before they even get chance to fill it out, so I changed the above to be the below. This then checks that each field has it minimal length of value before it validates the whole date.

if ((dayBirth.val().length >= 1) && (monthBirth.val().length >= 1) && (yearBirth.val().length > 3)) {

$(fullBirth).valid()          

 }

You can now see the whole code for the validation method. This will validate each field on its own, while also validating the whole date. You will need to add your own method for validating the full date, but if you read up on the library this should be easy.

/// Check Valid date
$.validator.addMethod("vailddatefield",

function (value, element, params) {

var dateValue = parseInt(value, 10);

//Get max and min dates
var Min = parseInt(params[0], 10);
var Max= parseInt(params[1], 10);

//validate full date
var day = $(params[2]);
var month = $(params[3]);
var year = $(params[4]);
var fullDate= $(params[5]);

//enter full date
$(fullDate).val($(day).val() + '/' + month.val() + '/' + year.val());

//Validate full date
if ((dayBirth.val().length >= 1) && (monthBirth.val().length >= 1) && (yearBirth.val().length > 3)) {

$(fullBirth).valid();

}

return this.optional(element) || (dateValue >= Min && dateValue <= Max);

},"Please enter a valid age"

);

Below here you can then see the example of calling the new methods for Month and for the full date. You can always also add more validation methods.

//Month required
$(".validate-month").rules("add", {

vailddatefield: [1,12,'.day','.month','.year','.fulldate'],
messages: {

vailddatefield:  'Please enter a month between 1 and 12'

}

});

//full date
$(".validate-date").rules("add", {

vailddate: '',
messages: {

vailddate:  'Please enter valid date'

}

});

Any thoughts and other methods people have seen can be shared in the comments section below.

ARIA Control JavaScript Library

This is a library to automatically inject the standard for screen readers mark-up ARIA. ARIA is Accessible Rich Internet Applications which is a way to make websites and applications more accessible to people with disabilities.

This libraries purpose is to automatically inject the necessary tags and commands to the users mark-up, so that it meets the standards as much as possible. There are also commands for the users to inject the methods on to specific parts if the library does not get them automatically. Also the automatic functionality can be turned off if only partly needed.

Download the library on GitHub 

View the examples on CodePen

Here are some helpful links about ARIA to help understand the tags and their values.

 

ARIA Control Library V1 Method Breakdown

Hidden (has auto)

This detects all the elements that are ‘display:none’ and/or ‘visibility:hidden’. It will then add the ARIA ‘aria-hidden’ and give it a role of ‘presentation’. This makes the element hidden from screen readers. There is also a method to make the element un hidden if the state changes.

Hidden Message (has auto)

This method uses the given class in the options to make the element display off the page. This means that the screen reader can see the message and read it out, but sighted users won’t be able to see the message. This is useful if you want to give extra information only to the users using a screen reader.

Notifications

This sets the attributes for ‘aria-atomic’, ‘role’ and ‘aria-live’. These are the attributes best served as a notification.

Alert (has auto)

This is for error messages and other alerts to the user. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: rude’. This can be automatically run with a set class.

Warning (has auto)

This is for warning messages and other none critical alerts to the user. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: assertive’. This can be automatically run with a set class.

Message (has auto)

This is for any message that is not critical like a success message. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: polite’. This can be automatically run with a set class.

Required (has auto)

Any element, usually inputs, that has the attribute ‘required’ on them will have the ARIA tag ‘aria-required’ added to the element. This can also be done manually by passing the class.

Popup (has auto)

With this method you need to set up the popup classes for the control and the popup. It is mainly aimed at the tooltip example, e.g. if you click in a field and then a tooltip shows. The method will give the control the aria tags to show it has a popup and the tooltip the tags to show what controls it. You can also pass the role type, but by default it is ‘tooltip’.

Show and Hide Popup

These are more helper methods to the above. When the popup shows or hides you can call these method to update the elements settings.

Checked Elements (has auto)

Both Checkboxes and Radio buttons will automatically have the check item injected with the ARIA ‘aria-checked’. This marks if the element is checked or not, for which the change event is also added to all of the elements so if it becomes checked or unchecked then it is updated.

Disabled (has auto)

Any disabled element will have the ‘aria-disabled’ tag added to it.

Selected Option (has auto)

This will make all the options in a select element ‘aria-selected: false’ then find the selected option to set it to true. It also adds the event change to detect when the selected has changed and updates them.

Max and Min (has auto)

This will mainly be for inputs with a max or min value. It finds if they have a value then puts them in their relative tags, either ‘aria-valuemin’ or ‘aria-valuemax’.

Navigation (only has auto)

A complex one, but easy to set up. With all the correct settings this can add the tags to show up to screen readers as a navigation. It will also tag the links as menu items and the sub menu as well as being a popup. It uses the hover event to detect when the sub menu is being shown.

Button (has auto)

This will detect the all button types and add its role as ‘button’

 

ARIA Control Library V1 Options Breakdown

autoDetect (default = true)

This determines if to automatically tag the elements or to only allow manual running.

alertClass (default = .acAlert)

Used for the auto detection for Alert Notifications.

warningClass (default = .acWarning)

Used for the auto detection for Warning Notifications.

msgClass (default = .acMsg)

Used for the auto detection for Message Notifications.

popupClass (default = .acTooltip)

The class of the popup or, as the example was, the tooltip.

popupCtrlClass (default = .acTooltipCtrl)

The element that triggers the popup or tooltip to show.

popupType (default = tooltip)

The role of the popup.

hiddenMsgClass (default = .acHiddenMsg)

The class of any hidden messages that don’t show to slighted users.

navClass (default = .acNav)

The navigation containers class.

navParentClass (default = .acSubNav)

The top level links class.

navSubNavClass (default = .acSubMenu)

The sub menu class.

Galen Framework Hover in JavaScript

A bit of a small audience for this one, but a project I was put on wanted us to use the Galen Framework to test their UI. For people who do not know what this framework is, it is a method of writing acceptance code that matches up to the output in the browser window. This can be coded to work for all different device, sizes and URLs. One hard space I came to was to action the hover state of an element and then test it.

If you would like to read up more about the Galen Framework first then you can find all the information you need on the website.

To test you can either run it in the Galen syntax to run in the Command Prompt or you can also run it using JavaScript. I opted of the Galen Syntax for no real reason, but there was a method to action the hover in the JavaScript version.

Ivan Shubin, the creator of the Galen Framework, point me here for the example.

load("init.js");

load("pages/WelcomePage.js");

 

testOnAllDevices("Welcome page", "/", function (driver, device) {

new WelcomePage(driver).waitForIt();

checkLayout(driver, "specs/welcomePage.gspec", device.tags);

});

 

testOnDevice($galen.devices.desktop, "Menu Highlight", "/", function (driver, device) {

var welcomePage = new WelcomePage(driver).waitForIt();

logged("Checking color for menu item", function () {

checkLayout(driver, "specs/menuHighlight.gspec", ["usual"]);

})

 

logged("Checking color for highlighted menu item", function () {

welcomePage.hoverFirstMenuItem();

checkLayout(driver, "specs/menuHighlight.gspec", ["hovered"]);

});

});

You can see the ‘hoverFirstMenuItem’ that actions the hover. This is built into the Framework that comes with the JavaScript. You can find more about the API and the ‘hover’ method on the Reference Guide for JavaScript.

However I was trying to use the Galen Framework in the command prompt, which can inject JavaScript into the page that runs once the page has loaded. The first idea I had then was to run a ‘hover’ action, which because the site I was running it on has Jquery loaded I could use like below:

$(document).ready(function () {

//hover links

$('a').trigger('mouseenter');

$('a').trigger('mouseover');

$('a').trigger('hover');

$('a').hover();

});

Though as you can see I went a bit overboard trying these all out as none of them seemed to work. I knew the Jquery was working as I was able to run other method to do click events and other thing. After some searching I found a method.

I found a way to get all the style sheets and then search through them. Once I could search them I could find out what the ‘hovered’ styling was for that element. Then I could extract the styling and inject it onto the element, so now its standard style becomes its hovered style.

You can see the below method that I use ‘document.styleSheet’ to loop through each style sheet, then get each rule and loop them. If the class I am looking for is found the I user ‘cssText’ to get all the styling from the rule. This does come back as ‘{background-color:blue}’ so the response text is stripped down to just the CSS.

function getStyle(className) {

            var c = '';

            for (var i = 0; i < document.styleSheets.length; i++) {

try{

                var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;

                if (classes) {

                    for (var x = 0; x < classes.length; x++) {

                        try {

                            if (classes[x].selectorText.indexOf(className) > -1) {

                                var s = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;

                                s = s.substring(s.indexOf("{") + 1);

                                c += s.substring(0, s.indexOf("}"));

                            }

                        } catch (ex) {

                        }

                    }

                }

                        } catch (ex) {

                        }

            }

            return c;

        }

You will notice there is a few try catches in the loops, these are because some style sheets it picks up are not accessible so they create an error in the JavaScript. The try catches mean it can keep looping on through the ones it can access instead of breaking out. Another bug fix is where it uses ‘rules’ or ‘cssRules’ and ‘.cssText’ or ‘.style.cssText’. This is due to different browser standards, some of the browsers use one set and some use the other, this prepares for either case when your tests run.

Below is how the full code sits together and can be used. You can see I invoke the method by passing ‘a:hover’ as it is the hover state I need to access to the link.

$(document).ready(function () {

function getStyle(className) {

            var c = '';

            for (var i = 0; i < document.styleSheets.length; i++) {

try{

                var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules;

                if (classes) {

                    for (var x = 0; x < classes.length; x++) {

                        try {

                            if (classes[x].selectorText.indexOf(className) > -1) {

                                var s = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;

                                s = s.substring(s.indexOf("{") + 1);

                                c += s.substring(0, s.indexOf("}"));

                            }

                        } catch (ex) {

                        }

                    }

                }

                        } catch (ex) {

                        }

            }

            return c;

        }

        //all links

        $('a').attr('style', getStyle('a:hover'));

});

No more desktop 2016?

They have said that this is the year of responsive websites and so do you wonder if next year there will only be mobile device websites? If every one goes on their mobile  and tablet devices all the time then is there a need to worry about desktop?

When I first started website developing there was no real need to develop for mobile devices. They were not really used for website searching and product browsing. This was because of the device speed, roaming speed and also it was just not easy with them phones. As technology for the devices have grown to become mini computers, cameras, controllers and a lot more, the web developing standards have also growth.

The stats show that over the past year more people are browsing and shopping on mobile devices including tablets, mobiles and soon to be watches. This has then brought focus to the developers making a website mobile responsive a want to a must. If you do not make your website mobile responsive then not only will it not appear great to the users of the website, but search engines like Google will see it as a negative. Read my post about responsive website development to see why responsive is a must and how best to do it by Google’s standards.

If the mobile devices are on such a rise with tablets and mobiles being cheaper to buy, then will the developing needs switch. Like when there was no need to for phone and tablet design/development, will it turn to the other way when you do not need to developer or design for desktop?

//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js

(adsbygoogle = window.adsbygoogle || []).push({});

When you start designing would you start with the mobile device design and have the desktop as an after thought? Would you even sell mobile websites and then the desktop as a bonus?

I think the desktop will either always stay or at least until the technology really does boom in mobile devices. There are always the hardcore gamers, programmer and even the older generation that want to use a desktop, plus need to for the power. You can’t beat a desktop or even a laptop on power, speed and battery life compare to a mobile device, so there will always be a demographic. Though technology will advance and could change this.

What do you think? Do you think that you will still be developing or designing for desktop devices in the next few year?

View the Source Code of Mobile Devices

Do you need to know what you mobile website is producing, but on the phone itself? Then here are the best ways I have found to inspect you mobile phone or tablets HTML. I have found how to inspect the HTML source of multiple platforms including iPhone, Android and more.

iOS (iPhone/iPad)

Let’s start with the best one and that is the iPhone and iPad. This only works on these devices and is totally worth it. Start by bookmarking the page you are on and calling it ‘View Source Code’ or what ever you want to call it.

Once you have it bookmarked, copy the JavaScript below into you clipboard. Now go to the bookmark you just created and edit the URL. Delete the URL currently in the field and overwrite it with the JavaScript you just copied.

javascript:(function(){var d=window.open(‘about:blank’),a=d.document;a.write(‘<!DOCTYPE html><html><head><title>Loading Source</title></head><body></body></html>’);a.close();var b=a.body.appendChild(a.createElement(‘form’));b.setAttribute(‘method’,’post’);b.setAttribute(‘action’,’http://ole.michelsen.dk/viewsource/?uri=’+location.href);var c=b.appendChild(a.createElement(‘input’));c.setAttribute(‘type’,’hidden’);c.setAttribute(‘name’,’DOM’);c.setAttribute(‘value’,encodeURIComponent(document.documentElement.innerHTML));b.submit()})()

Now when you go to a website you want to view, simply select the ‘View Source Code’ bookmark and a new tab will open with your HTML in.

Android

Another one I have found for Android is much simpler, but has not been fully tested by myself as I am an iPhone user. If you copy the code below into you clip board, then paste it in the address bar of the website you wish to see the source code of.

javascript: alert(document.getElementsByTagName(‘html’)[0].innerHTML);

Once loaded you should be able to see the HTML source of that page. This method is simpler than the iOS, but you will have to have this snippet saved somewhere to keep entering it.

Through the code

If you have access to the code then you can simply add the above code in the JavaScript tag to alert the HTML, but it doesn’t work that well. If you alert the whole HTML then it shows you as much as it can, but as there is so much HTML it doesn’t show everything.

 alert(document.getElementsByTagName(‘html’)[0].innerHTML);

Windows Phone

I have not found a way to view the source code on a Windows Phone yet, but if anyone knows then please comment here to help others.