Friday, April 3, 2009

Definitive Javascript RegEx Validation for Butchers

This comes back to bother me now and then - so I decided to put together a few snippets to use as base in case of client validation with RegExes.

First of all the core snippet, which takes text to validate and a regex and returns a boolean:

function regexMatch(regEx, stringToValidate)
{
var oREGEXP = new RegExp(regEx);
return oREGEXP.test(stringToValidate);
};

Often you will be validating a text field - so here's other two functions using the previous one:

function textFieldVisualRegexValidation(textElement, regEx)
{
var returnValue = false;

if (regexMatch(regEx, textElement.value))
{
textElement.style.backgroundColor = "green";
returnValue = true;
}
else
{
textElement.style.backgroundColor = "red";
}

return returnValue;
};

function textFieldRegexMatch(ctrlName, regEx)
{
var elem = document.getElementById(ctrlName);

return textFieldVisualRegexValidation(elem, regEx);
};

Some event will call textFieldRegexMatch triggering the validation. You can customize textFieldVisualRegexValidation to perform some action in case of validation succeeded or failed (I am setting the input field background to green.red but one could swap images or whatever).

You can hook up the above from (for example) the onBlur event of one of your textBoxes or any input field:

onblur="textFieldRegexMatch('yourInputFieldID', regExPattern)"

You obviously have to declare somewhere your regExPattern:

const regExPattern = "^[A-Z,a-z,0-9]{1,12}$";

I am sure there are better ways of doing the above but this is just meant as a reference to brutally Copy-Paste and tailor to your needs.

No comments: