Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Form Custom Validation - Check if at least one input is empty

Given a simple html form like this:

<form name="myForm" action="#sent" method="post" ng-app>
   <input name="userPreference1" type="text" ng-model="shipment.userPreference" />
   <input name="userPreference1" type="text" ng-model="shipment.userPreference" />
   <input name="userPreference1" type="text" ng-model="shipment.userPreference" />
... submit input and all the other code...
</form>

I need your help to know how to check on validation time, if at least one of the inputs is empty. The desired validation is the following. The user must complete at least one a preference.

Using jQuery this:

if ( $("input").val() == "" ) {

Works ok, but would like to figure out how to do the same thing using angular.

Thanks so much in advance,

Guillermo

like image 281
Guillermo Avatar asked Aug 15 '13 20:08

Guillermo


2 Answers

You can set the "required" in the input elements and style / code how you want to handle with $valid of a form. Check out http://dailyjs.com/2013/06/06/angularjs-7/

like image 67
Mouli Avatar answered Nov 05 '22 05:11

Mouli


So the idea is to disable the submit button if all inputs are blank. You can do like this

<form name="myForm" action="#sent" method="post" ng-app>
   <input name="userPreference1" type="text" ng-model="shipment.userPreference1" />
   <input name="userPreference1" type="text" ng-model="shipment.userPreference2" />
   <input name="userPreference1" type="text" ng-model="shipment.userPreference3" />

   <button type="submit" ng-disabled="!(!!shipment.userPreference1 || !!shipment.userPreference2  || !!shipment.userPreference3)">Submit</button>
</form>

!!str is to force to convert str to a boolean value. And both !!null and !!"" are evaluated to be false.

Demo

like image 29
zs2020 Avatar answered Nov 05 '22 04:11

zs2020