Yes, you can do it by directive too, but just for validating just text contains two characters or not ng-pattern
would be better way to do.
Here your html would be using (.*?[a-zA-Z]){2,}
this pattern.
HTML
<input type="text" ng-model="fistname_lastname" max-length="30"
ng-pattern="/^(.*?[a-zA-Z]){2,}$/" placeholder="add new todo here"/>
Working Fiddle
Update
If you want to stop your form from submitting,, then you need to no worry about it. Angular internally manages this for you. Whenever you mention ng-pattern
against any form field, angular creates object for that field (field should have name
and ng-model
attribute), that object is responsible for the validity of particular field. As as ng-pattern
regx doesn't gets satisfied, angular make that field as invalid
, means it append ng-invalid-pattern
& ng-invalid
class. Resultant the form also gets invalid. and now if you can look at form object you will find that form gets invalid
by using syntax form.$valid
on html.
HTML
<form name="form" ng-submit="submit()">
<input type="text" ng-model="firstname_lastname" size="30" ng-pattern="/^(.*?[a-zA-Z]){2,}$/" placeholder="add new todo here"/>
<button type="submit">Submit</button>
</form>
Controller
$scope.submit = function(){
if($scope.form.$invalid) //here you can stop use from submitting for by checking validity
alert('Form is invalid'); //form is invalid
else
alert('Form is valid');//here you can do actual submit to server
}
Updated Fiddle
Hopefully this could help you, Thanks.