Search code examples
regexangularjsvalidationng-pattern

angular ng-pattern match any non-word, non-space, non-digit not working?


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>

<div ng-app>
    <form class="edit-segment edit-form" name="form">
        <input type="text" class="form-control" ng-model="dname" name="name" maxlength="100" ng-pattern="/[A-z0-9 ]+/" ng-required='true' />
        <output>{{form}}</output>
        <output>{{dname}}</output>
        <output>{{form.name.$valid}}</output>
    </form>
</div>

the pattern is:
/[A-z0-9 ]+/

For some reason this angular-infused html is not acting the way i'm expecting. What I'm expecting to happen is that as soon as a user enters a non-word, non-digit, non-space character, that the input becomes invalid, so $form.name.$valid should be false.

Instead what happens is, as long as what you input contains a letter, number or space, the input becomes $valid becomes true.
so:
lkajskdjf<.?{}
is valid

.,.,..,{}{][].,
is not valid.

.,.,..,{}{][].,\
is valid.

?>?./..,./9k
is valid.

kjkljd lkjsdf 90
is valid.

The only one that should be valid is the last one... My understanding of ng-pattern, which is evidently wrong, is that the input only valid as long as the characters entered match the regex in ng-pattern.

What's going on here?
Why is the behavior I'm expecting not the behavior that I'm getting?


Solution

  • The pattern should probably be /^[A-z0-9 ]+$/, where the ^ and $ symbols mean "begins with" and "ends with" respectively. This will mean that the regex will match exactly and only your character class.