Reputation: 760
I use a regular expression to validate some form inputs with angularjs. I use the ng-pattern
for that.
<input type="text" ng-pattern="/^([A-z]){3}$/">
<button type="submit" ng-disabled="demoForm.$invalid">Ok</button>
If i type anything not matching the expression it is not valid (as expected). If i type what is matching the pattern it will be valid (as expected).
But it doesn't work as expected at all. If i type nothing (empty text input) the form is valid, and that is what i want to avoid: It shouldn't be valid.
Any suggestions?
Upvotes: 0
Views: 55
Reputation: 2007
You'll need to give the input an ng-model
attribute for Angular form validation to recognize it. You may also want to give the input a name
attribute for more control. See Angular Input documentation.
This example should demonstrate how ng-model
and name
can be used for form validation. Note that I've also adjusted your regex and made the input required
.
var myApp = angular.module('myApp', []);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form name="demoForm">
<input type="text"
ng-model="myValue"
name="myInput"
ng-pattern="/^[A-Za-z]{3}$/"
required />
<button type="submit" ng-disabled="demoForm.$invalid">Ok</button>
<div>Input valid? {{demoForm.myInput.$valid}}</div>
<div>Form valid? {{demoForm.$valid}}</div>
<div>Model value: {{myValue}}</div>
</form>
</div>
Upvotes: 1