Today, I would like to share a useful code that could help when you need to know if a color is correctly entered in an input field. So, here is an example of how to validate an HTML hexadecimal color by using a regular expression in JavaScript.
The regular expression to accomplish this task is:
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Explanation:
^ – Represents the beginning of the string
# – Number symbol (to accept only colors starting with “#”, like “#33cc55”)
( – Indicates the beginning of the group
[A-Fa-f0-9]{6} – Accepts six characters: letters among A to F, a to f or digits.
| – An “OR” condition
[A-Fa-f0-9]{3} – Accepts three characters: letters among A to F, a to f or digits.
) – Indicates the end of the group
$ – Represents the end of the string
Now, for testing we need a little HTML like this:
<div class="testing"> <input id="links_color" name="links_color" value="#445566" /> <a id="validate" class="btn" href="#">Validate</a> <div id="errors_output"></div> </div>
And this code uses the regular expression in JavaScript:
(function($){
$(document).on('ready', function(){
function checkRegexp ( o, regexp, n, errors_output ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" ); // Uses a jQuery UI class
errors_output.html("Error: " + n);
return false;
} else {
errors_output.html("Correct! ");
return true;
}
}
$("#validate").on('click',function(){
var links_color = $("#links_color"), // This read a DOM object (input)
errors_output = $("#errors_output");
var valid = checkRegexp(
links_color,
/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,
"Enter valid colors like #42AB56",
errors_output
);
});
}); // ends document ready
})(jQuery);
If you prefer to test this code in a complete example you can download it! http://www.alex-arriaga.com/wp-content/uploads/files/compressed/demo-regex-example.zip
That’s it!
Be happy with your code!
—

Wip Pensador liked this on Facebook.