zenwarrior zenwarrior - 1 year ago 76
AngularJS Question

adding directive to form breaks pattern rule

I have a simple log-in form. username must be in e-mail form, so there is ng-pattern constraint.

HTML form:

<form name="loginForm">
<div class="form-group">
<input type="text" name="username" ng-model="user.name" ng-pattern="/^[_a-zA-Z0-9-]*@[a-zA-Z0-9-]+([\.a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,4})$/" required class="input-text full-width" placeholder="email address"> <span ng-show="usernameError"><small style="color: red">Enter E-mail Address</small></span>

<div class="form-group">
<input type="password" name="password" ng-model="user.password" required class="input-text full-width" placeholder="password"> <span ng-show="passLenError"><small style="color: red">Password can be 6 to 15 characters long, and must have at least one letter and one digit</small></span>
<div class="form-group">
<a href="#" class="forgot-password pull-right" ng-click="passwordRecovery=true">Forgot password?</br></a>
<div ng-show="false" class="checkbox checkbox-inline">
<label> <input type="checkbox"> Remember me
<div class="text-center">
<button type="submit" ng-click="loginUser()" class="full-width btn-medium">LOGIN</button>

I added this directive to the form, so when enter is pressed form will be submitted.

AngularJS Directive:

loginApp.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$eval(attrs.ngEnter, {'event': event});


Problem is when I add ng-enter to the form ng-pattern doesn't work. for '$scope.loginForm.username.$error.pattern' instead of true/false value I get undefined. ng-required still works.

<form name="loginForm" ng-enter="loginUser()">

Answer Source

You can use ng-submit and set type of button is submit in this case:

<form name="loginForm" ng-submit="loginUser()">
   // some thing
   <button type="submit" class="full-width btn-medium">LOGIN</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download