Search code examples
javascriptjquerycssangularjsangularjs-ng-pattern

angularjs ng-pattern change css style of elements based on regex condition


In my angularjs form, I am checking the password pattern with a regex that checks for multiple conditions. Based on different condition checks of this regex, I want to change the css for one of the elements.

Jsfiddle link Here .

The source model that inspired this is from here.

This is my function to check the pattern against the regex :

$scope.passPatternCheck= (function() {
    var regexp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!#\$%&'\(\)\*\+,\-\.\/:;\<=\>\?@\[\\\]\^_`\{\|\}~]?)[A-Za-z\d!#\$%&'\(\)\*\+,\-\.\/:;\<=\>\?@\[\\\]\^_`\{\|\}~]{8,}/;
    return {
        test: function(value) {               
            return regexp.test(value);
        }
    };
})();

Some notes:

  • this regex don't check for the starting/ending spaces; this should also be adjusted
  • the ng-if that shows/hides the div of the conditions list is not currently working.

question:

I want to reproduce the same behaviour from the godaddy site account creation page. So the goal is to have the same css behaviour according to the condition completed. enter image description here

update 2:

my submit button of the form theForm should get disabled if any of the fields that are required are not filled out or an error in the patterns occurred:

<button type="submit" class="btn btn-primary"ng-disabled="theForm.$invalid" ng-click="submit()">
</button>

but with the Shantanu's answer, this is not yet possible.


Solution

  • Adding one regex for ng-pattern will not achieve it. Because if regex test fails then we would not know exactly which case of all those checkbox conditions failed. You've to handle different regex for each conditions & check them in either custom directives (using $validators) and create custom validators for that each validation OR you can check those condition on change of password input field inside controller & create one object with different properties as Boolean values for those validation conditions.

    I've created jsfiddle for 2nd method: http://jsfiddle.net/shantanu_k/Lnupw3p2/7/

    Updated based on updated question (form has to be invalid if any conditions fail & thus making submit button disabled): http://jsfiddle.net/shantanu_k/Lnupw3p2/10/