Search code examples
javascriptangularjsangularjs-ng-pattern

How to debug ng-pattern


I'm working on custom form validation for an Angular application using ng-pattern.

In my form I have:

<form name="jobsForm" id="jobs-form">
    <div jobs-form jobs="jobs">
        <div ng-form="jobsForm">
            <div class="form-group">
                <label for="source_path">Source Path:</label>
                <input type="text" class="form-control" name="source_path" id="source_path" ng-model="jobs.source_path" ng-pattern="path_regex" required>
                <span class="input-error" ng-show="jobsForm.source_path.$invalid.pattern">INVALID PATH</span>
            </div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary-red" ng-click="submitJob()">Submit</button>
</form>

In my controller I define path_regex:

$scope.path_regex = /^[a-zA-Z]:\\(((?![<>:"\/\\|?*]).)+(\\)?)*$/;

When I try it out, nothing works. What is the best way to debug this? Is it possible to put a breakpoint in and check my values for ng-show?


Solution

  • For sure you can. If you look at the angularJS documentation for ng-pattern and then click on the "View Source" button at top right, you will see the source code. There isn't much to this directive. Search for this code:

    ctrl.$validators.pattern = function(modelValue, viewValue) {
            // HTML5 pattern constraint validates the input value, so we validate the viewValue
            return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
    };
    

    So you can see there is a function being assigned to the array of $validators on the model controller. When data changes, all of the $validators will be executed.

    Now go to the chrome debugger, sources panel and search for one of these lines of code and in your un-minified angular.js file. Put a breakpoint in this same function to make sure that your regex gets to the test.