Reputation: 7008
I want to show error message when user enter invalid input in text field.
Right now I am using:
Pin:<input type="text" class="form-control input-sm" ng-pattern="numOnlyRegex" name="pin" ng-model="pin" required placeholder="Pin"/>
<span style="color:red" ng-show="myForm.pin.$invalid">Only number are allowed</span>
<input type="Submit" class="form-control btn btn-success" ng-disabled="myForm.$invalid" value="Submit" />
Controller:
<script>
angular.module('myApp', []).controller("numOnlyRegex", function ($scope)
{
$scope.numOnlyRegex = /^\d+$/;
});
</script>
But the above way I am trying shows a static message below the input text-field. What I want is when the user enters letters instead of numbers it should show error message like "only numbers are allowed" else there it should not show any error message.
ng-show
method shows static message when the input is empty but I want to show error only when there is error(more realistic way)
Upvotes: 2
Views: 22963
Reputation: 220
angular.module('myApp',[]).controller('myFormController',['$scope',function($scope){
$scope.myInputVal='';
}])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body ng-app="myApp">
<div ng-controller="myFormController">
<form name="myForm" >
<input type="text" ng-model="myInputVal" ng-pattern="/^[0-9]*$/" name="myInputVal"/>
<span ng-show="myForm.myInputVal.$error.pattern">Only Numbers are allowed</span>
<span ng-show="!myForm.myInputVal.$error.pattern">{{myInputVal}}</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
</div>
</body>
Upvotes: 0
Reputation: 7425
You may use the $error.pattern on your form to display specific error message
<span style="color:red" ng-show="myForm.pin.$error.pattern">Invalid Input</span>
Following are some other examples of $error
myForm.useremail.$error.email ==true
// When useremail field does not contain a real email.
myForm.username.$error.require ==true
// Only if the username field is left blank.
Here's the plunkr
Upvotes: 5
Reputation: 13997
Angular allows you to target specific errors. In this case you can use the invalid pattern error:
<span style="color:red" ng-show="myForm.pin.$error.pattern">Only number are allowed</span>
This way it will only show when the error is on the pattern validation.
See this JSFIDDLE
Upvotes: 2