I just want to validate textbox in my project in such a way so that a user could not enter any value other than characters.
Asked
Active
Viewed 9,883 times
0
-
http://stackoverflow.com/questions/15554915/angular-directive-ignore-non-numeric-input – Mike Ohlsen Jan 29 '14 at 14:32
1 Answers
2
Hackish? way, $watch the ng-model in your controller:
<input type="text" ng-model="myText">
Controller:
$scope.$watch('myText', function() {
// put logic to strip out all non-character characters here
if ($scope.myText ... regex to look for ... ) {
// strip out the non-characters
}
})
Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://stackoverflow.com/a/14425022/215945
Don't try to use ng-change -- it will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)
Update: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.

Community
- 1
- 1

Mark Rajcok
- 362,217
- 114
- 495
- 492
-
It seems u didn't understand my problem. I want that user could not enter any value other than character in the textbox. So i think here we have to use onkeypress function. Wht u say?? – user2013463 Feb 03 '13 at 06:50
-
1I believe the two solutions I provided should work. I just updated my answer with information about ng-pattern. If you can't get it to work using one of these three solutions, please post a [fiddle](http://pkozlowskios.wordpress.com/2012/08/12/using-jsfiddle-with-angularjs/) or a [plnkr](http://plnkr.co/edit/) of what you tried. – Mark Rajcok Feb 04 '13 at 15:17
-
I already use ng-pattern for this purpose & it served me well for validating purpose but actually now i want that user couldn't even type anything in textbox apart from characters. Could you please help me with this?? – user2013463 Feb 05 '13 at 11:13
-
See http://stackoverflow.com/a/15556249/215945 where a directive was written to prevent non-numeric characters from being entered. Just change the regex in the directive to allow only characters. – Mark Rajcok Mar 21 '13 at 19:48