Reputation: 5144
Here is a simple form with an input that is required:
<div ng-controller="MainCtrl">
<form name="add-entry" press-enter="add_entry()">
<input type="text" ng-model="amount" required />
<!-- <input type="submit" value="Add" /> -->
</form>
</div>
The form uses a custom pressEnter directive because I'm reluctant to use an <input type="submit" />
in my markup, even if I can hide it with absolute positioning and whatnot (using ngSubmit
instead of pressEnter
would require one of these to fire the expression).
angular.module('app', []).directive('pressEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.pressEnter);
});
event.preventDefault();
}
});
};
});
The problem now is that the required
attribute is also not taken into account without ngSubmit
. See http://jsfiddle.net/w6QHD/12/ -- you can see that pressing enter on an empty input still fires add_entry()
. The form is validated only when using ngSubmit
instead of pressEnter
and uncommenting the <input type="submit">
.
How do I make form validation work without using ngSubmit
?
Upvotes: 2
Views: 9194
Reputation: 60416
It's not really clear whether you want to rely on HTML5 validation or on AngularJS validation. If it's the Angular validation that you want to use than you may simply use FormController to trigger the validation and error messages:
<div ng-controller="MainCtrl">
<form name="form" press-enter="add_entry()" novalidate>
<input type="text" name="amount" ng-model="amount" required />
<span ng-show="submitted && form.amount.$error.required">Amount is required</span>
</form>
</div>
function MainCtrl($scope) {
$scope.add_entry = function() {
$scope.submitted = true;
if($scope.form.$valid){
console.log("Entry added");
}
}
};
Upvotes: 3