Allen Luce
Allen Luce

Reputation: 8389

ngMessages/angular validation not working

I'm getting neither a value emitted by the template fragment nor functioning validation. My Jade template:

doctype html
html(lang='en', ng-app="Validate")
  head
    script(src='#{cdn_path}/angular.js/1.3.11/angular.js')
    script(src='#{cdn_path}/angular.js/1.3.11/angular-messages.js')
    script.
      angular.module('Validate', ['ngMessages']);
  body
    .container
      form(method="POST", action="/apply", name="myform", novalidate="")
        pre myform.name.$error = {{ myform.name.$error }}
        input.form-control(name="name", required="", pattern=".*[a-zA-Z].*", minlength=5)
        ng-messages(for="myform.name.$error")
          ng-message(when="required") Required!
          ng-message(when="min") Too small!
        input.btn(type='submit')

The resulting HTML: http://plnkr.co/edit/McyMXwW1b2Ae7kkwQ1sP

I'd like to avoid custom directives or much in the way of additional Javascript. What am I doing wrong?

Upvotes: 7

Views: 16922

Answers (2)

mnishiguchi
mnishiguchi

Reputation: 2241

I just have the same issue and solved it. I want to share it so no one will waste an hour like me.

Please ensure the following:

1. Load the ngMessages module

<!-- Load Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>

<!-- Load ngMessages -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular-messages.min.js"></script>

2. Inject ngMessages into our application module

angular.module( "app", [ "ngMessages" ] );

3. Try newer versions For some reason, Doug Luce's code gets working just by changing versions to e.g., 4.11!

Upvotes: 17

squiroid
squiroid

Reputation: 14027

This is happening because you didn't bind ng-model with the input :-)

 <input name="name" ng-model="name" required="" pattern=".*[a-zA-Z].*" minlength="5" class="form-control">
        <ng-messages for="myform.name.$error">
        <ng-message when="minlength">Too small!</ng-message>
        <ng-message when="required">Required!</ng-message>

Plunker:- http://plnkr.co/edit/kmNkfhdVOHQsstj6dpPT?p=preview

Upvotes: 19

Related Questions