AngularJS conditional “require” validation

Shame on me: I only noticed about ng-required after almost a year of using AngularJS! So what’s the big deal you ask…

Imagine this: you have a form with three fields, and the form is to be valid when at least one of the fields is specified.

You could handle validation yourself using “the old way”: you write JavaScript code that checks the condition. Then you mess with the instance of FormController that AngularJS has created for you (you know, the structure you can access using $scope.myForm) in order to set the form to valid or invalid. Sounds tedious and messy? It is.

Or you could use ng-required, which sets the input or textarea element as required if the expression evaluates to true. Now you can see how neat the conditional validation’s solution can be!

In practice, this is how it happens.

Imagine you have a contact form where you want the user to leave you either its email, its mobile number or its physical address. One of those is enough, as long as you have a way of somehow keeping in touch.

The form code would look something like:

The scope method called by ng-required must return true if none of the fields is specified, false if at least one field is filled. So the controller code could be similar to:

And that’s all there is to it.

As soon as one of the elements is filled, the isOneContactRequired() method returns false, making all the other contact fields not required anymore.

That in turn makes the form valid, which makes the “Send!” button appear. Easy!

Of course, nothing prevents you from combining this with other, non-conditional validations. For example, let’s say we want to make the contact text mandatory (which would make sense, really!). We just add “required” to the field so that the user needs to type a message AND fill one of the three contact fields:



    • Yep. I’ve been happily developing in AngularJS for more than a year now, and I have just noticed the directive! You would not believe what I hacked before I found about ng-required (and thanks heavens that hack o’ mine never had the chance to go in production!).
      Let that be a humility lesson to me.
      Oh and thank you for pointing me to your StackOverflow question: I definitely should have seen that one… 😉

Comments are closed.