views:

91

answers:

2

I've written a method to handle regex validation in AX2009. Problem is that it always returns false, no matter what the expression or input string. Returns no errors, just 'false' Mind taking a look? I'm probably missing something simple.

This post has been updated to included the corrected method, without the error, so you can cut and paste the code for use in your project. BP compliant and ready for use. - Enjoy

static boolean validateMe(str regexFilter, str _testString)
{
    System.Text.RegularExpressions.Match regExMatch;
    boolean retVal;
    str regExpression;
    ;

    //See if any of the static expressions were selected
    switch (regexFilter)
    {
        case 'integer' :
            regExpression = '^\\d+$';
            break;
        case 'rgbcolor' :
            regExpression = '^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\,([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\,([01]?\\d\\d?|2[0-4]\\d|25[0-5])$';
            break;
        case 'number' :
            regExpression = '^(\\d+\\.?\\d*|\\d*\\.?\\d+)$';
            break;
        case 'email' :
            regExpression = '^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$';
            break;
        case 'phone' :
            regExpression = '^(\\()?(\\d{3})(\\)|-)?([0-9]{3})(-)?([0-9]{4}|[0-9]{4})$';
            break;
        case 'nopunctationphone' :
            regExpression = '^\\d{10}$';
            break;
        default :
            //No static expression matched, use the passed-in value
            regExpression = regexFilter;
    }

    //see if the string matches
    if (_testString != '')
    {
        //see if string matches expression; validation is good
        regExMatch = System.Text.RegularExpressions.Regex::Match(_testString, regExpression);
        retVal = regExMatch.get_Success();
    }
    else
    {
        //string does NOT match expression; validation fails
        retVal = false;
    }

    return retVal;
}
A: 

Could it be that you need to escape the backslashes inside strings?

regExpression = '^\\d*$';

etc.

Tim Pietzcker
Unfortunately, already tried that. FYI: the email regular expression is a copy/paste from Classes > SysEmailDistributor > EmailValidator. It even returns false for '.*' so I think there may be something wrong besides the expressions.
Brad
Tim is right, you need to escape backlashes like he did, or you can do it like this: regExpression = @'^\d*$';
Velislav Marinov
+2  A: 

You have swapped the variables it should be:

regEx = new System.Text.RegularExpressions.Regex(regExpression);
Velislav Marinov
Doh! Can't thank you enough. I stared at that code for hours. Funny how the simpler the problem is, the harder it can be to find. ; )
Brad