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.
1 Answer
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.
4 Comments
user2013463
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??
Mark Rajcok
user2013463
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??
Mark Rajcok
See 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.