Search code examples
javascriptregexteleriknativescript

Why is RadDataForm validation with regex always failing?


I am attempting to use Telerik's RadDataForm control to display a simple login form. I have it validating the email correctly but when I try and use a RegEx validator for the password, it's always failing. The regex I'm using has been used elsewhere without issue. The test password I'm using is "Tested12" which should pass. To summarize the test, the string should have at least an uppercase letter, a lowercase letter and a number. It should be at least 8 characters long.

The regex is:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})

Here's the json metadata I'm using to define the password field:

{
    name: 'password',
    displayName: 'Password',
    editor: 'Text',
    validators: [{ 
        name: 'RegEx',
        params: {
            'regEx': '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})',
            errorMessage: 'Passwords must be at least 8 characters long and contain numbers, uppercase letters, and lowercase letters.'
        }
    }]
}

I don't think it matters but I'm using the control from Nativescript UI in a Nativescript-Vue project.


Solution

  • Your regex only contains lookaheads, non-consuming patterns that only check if some text is there in the string, but they do not actually move the regex index and do not put matched text into the match value. The regex in the validation here must consume the whole string.

    The easiest way is to convert the length checking lookahead into a consuming pattern:

    'regEx': '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}'
                                                ^^^^^
    

    Actually, you may create better password regexps if you use the principle of contrast:

    'regEx': '^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=[^0-9]*[0-9]).{8,}'
    

    Details

    • ^ - start of string
    • (?=[^a-z]*[a-z]) - (a positive lookahead that performs a check once at the start of the string) after 0+ chars other than lowercase ASCII letters, there must be a lowercase ASCII letter
    • (?=[^A-Z]*[A-Z]) - (a positive lookahead that performs a check once at the start of the string) after 0+ chars other than uppercase ASCII letters, there must be a uppercase ASCII letter
    • (?=[^0-9]*[0-9]) - (a positive lookahead that performs a check once at the start of the string) after 0+ chars other than a digit, there must be a digit
    • .{8,} - 8 or more chars other than line break chars.