15

I'd like to prevent the user from clicking the button "Register" if the fields are not correct. Part of that is that certain fields must be filled. But the condition is starting to get a bit long:

<button class="btn btn-success" ng-click="register()"
    ng-disabled="signInForm.$invalid || form.firstName.length==0 ||
    form.lastName.length==0 || form.email.length==0 ||
    form.password.length==0 || form.passwordBis.length==0">Register</button>

How can I simplify that?

daemone
  • 1,183
  • 1
  • 17
  • 28
Elfayer
  • 4,411
  • 9
  • 46
  • 76

1 Answers1

26

I think what you need is to provide required attribute for your input fields inside your form, so until the fields are filled in the form signInForm will be invalid. Similarly you could provide other validation attributes on the inputs as well.

Example:-

  <input type="text" ng-model="firstName" name="firstName" required />
  <input type="text" ng-model="lastName" name="lastName" required />
  <input type="email" ng-model="email" name="email" required />
  ...
  ...
  <button class="btn btn-success" ng-click="register()" 
            ng-disabled="signInForm.$invalid">Register</button>
Selfish
  • 6,023
  • 4
  • 44
  • 63
PSL
  • 123,204
  • 21
  • 253
  • 243
  • Looks like you're right : http://jsfiddle.net/mgmp6L0b/ But in my case it doesn't work... Looks like I'm not using the same framework... I have AngularJS v1.2.25, and the email : "toto@to" is valid in my code and not in the JSFiddle example above. Also required in my code doesn't change the behavior... Any thought ? – Elfayer Oct 02 '14 at 14:18
  • I cant access fiddle can u paste in a plunkr. I knw there used to be a bug with email validator pattern... – PSL Oct 02 '14 at 14:26
  • I understand what you are saying, your issue has more to do with the html5 email validation and angular's If you do the same in the demo in official documentation as well you will see the same. https://docs.angularjs.org/api/ng/input/input%5Bemail%5D You can use your own pattern by providing `ng-pattern` – PSL Oct 02 '14 at 14:39
  • Ok, very funny... In plunker the email validation works as in my program : http://plnkr.co/edit/YcjlZpUwOgfVC0KyEQoM?p=preview Anyway, the required thing works, I had a conflict above the button in some input ng-class that probably made the thing not working. I didn't have any error to notice it, pretty hard to guess what is wrong while using angular directives, there are no errors on the console. – Elfayer Oct 02 '14 at 14:40
  • I've tried to find a good email pattern on the net, but it seems to be a complicated problem, there is no unique answer to this. =/ – Elfayer Oct 02 '14 at 14:42
  • No thats true. It completely is relative.. In my case we have our own custom pattern to include our domain as well.. So yes it differs – PSL Oct 02 '14 at 14:43