Determining if a form is valid using angular - javascript

I'm trying to determine if a form is valid or not using angular.
I have a form like this:
<form name="form" novalidate>
<p>
<label>Number: </label>
<input type="number" min="0" max="10" ng-model="test.number" required />
</p>
<p>
<label>Name: </label>
<input type="text" ng-model="test.name" required />
</p>
<button ng-click="sendTest(test)">Submit</button>
</form>
And, on the sendTest function I did:
angular.module('demo', [
]).controller('MainCtrl', function($scope){
$scope.test = {
name: 'das'
};
$scope.sendTest = function(test) {
console.log(form.$valid);
console.log(test.$valid);
}
});
The problem is that both form.$valid and test.$valid are undefined. I tried to do this following these examples:
http://dailyjs.com/2013/06/06/angularjs-7/
http://www.youtube.com/watch?v=J82OD76QhPo
Here's the complete code for this demo:
http://plnkr.co/edit/l0E62KPJu4Z2r15VNjJq

form gets added to the scope, try: console.log($scope.form.$valid)
BTW, it's called form because that's the value you have specified on the form tag's name attribute. You can also add name attributes to the input fields if you from your controller want to know the state of the specific fields.
Example: http://plnkr.co/edit/Ra98yIFYso94flDIqNCD?p=preview

Related

Disabled submit button if form is invalid angularjs

I currently have a form with many different inputs. In the example below I have created a form with two inputs for simplicity. I am trying to make it so my submit button is disabled when the form isn't valid - that is, when all the required inputs have not been filled out.
This is what I have tried so far:
angular.module('myApp', []);
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<form name="myForm">
<input type="text" placeholder="name" required/>
<input type="number" placeholder="age" required />
<input type="submit" ng-disabled="myForm.$invalid" />
{{ myForm.$invalid }} <!-- prints "false" -->
</form>
As you can see from the above snippet, myForm.$invalid is false even though I haven't filled out the required inputs yet. Is there some different property which will tell me if the required inputs have all been filled out?
I have looked at different posts such as this one but when I try and use myForm.$valid it just gives me the negated version of myForm.$invalid, which doesn't help much either.
You are missing ng-model in the form fields. You need to add ng-model as it detects the changes in the form fields.
Try this:
angular.module('myApp', []);
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<form name="myForm">
<input type="text" ng-model="name" placeholder="name" required/>
<input type="number" ng-model="age" placeholder="age" required />
<input type="submit" ng-disabled="myForm.$invalid" />
{{ myForm.$invalid }} <!-- prints "false" -->
</form>

ng-form inside ng-repeat not updating subform.$submitted

I am trying create forms inside ng-repeat, everything is working fine except submit button. Submit button placed in main form it is common for all sub forms.
If the submit button is clicked mainForm.$submitted gets updated but userForm.$submitted dose not changing. Is there any work around for that ?
angular.module("sampleApp", [])
.controller('sampleCtrl', function($scope) {
$scope.users = [{},{}];
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="sampleApp" ng-controller="sampleCtrl">
<form name="mainForm" novalidate>
<input type="text" name="school" ng-model="school" required>
main form input valid=>{{mainForm.school.$valid}}
<div ng-repeat="user in users">
<ng-form name="userForm">
<input type="text" ng-model="user.name" name="name" required>
sub form input valid=>{{userForm.name.$valid}} | sub form submit=>{{userForm.$submitted}}
</ng-form>
</div>
<button type="submit">Submit</button>
Form valid=>{{mainForm.$valid}} | Main From submit => {{mainForm.$submitted}}
</form>
</div>
Intro
So, I added a ng-click handler to the button so that you set the submitted status of the internal form as well.
The only difficult I had was to actually get the form reference, but I added the function $scope.setUserForm which is called with an ng-init. The solution pattern is from: https://stackoverflow.com/a/23862411/1688441
Also, please keep in mind you need an array of userForms to keep the references. On click you iterate through these elements and set the submitted.
Code
angular.module("sampleApp", [])
.controller('sampleCtrl', function($scope) {
$scope.UserForms = [];
$scope.setUserForm = function(form) {
$scope.UserForm = form;
$scope.UserForms.push(form);
}
$scope.forms = {};
$scope.users = [{}, {}];
$scope.handleClick = function() {
$scope.UserForms.forEach(function(element) {
element.$submitted = true;
});
};
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="sampleApp" ng-controller="sampleCtrl">
<form name="mainForm" novalidate>
<input type="text" name="school" ng-model="school" required>
input valid=>{{mainForm.school.$valid}}
<div ng-repeat="user in users">
<ng-form name="userForm">
<div ng-init="setUserForm(userForm);"></div>
<input type="text" ng-model="user.name" name="name" required>
input valid=>{{userForm.name.$valid}} | form submit=>{{userForm.$submitted}}
</ng-form>
</div>
<button type="submit" ng-click="handleClick()">Submit</button>
Form valid=>{{mainForm.$valid}} | From submit => {{mainForm.$submitted}}
</form>
</div>

how to check all fields are empty in angularjs

How to check all fields in the submit form ng-submit="submit(field)" is empty in controller.js? They consists of few textboxes and one select field.
I would want an alert box to occur if all fields are empty and select option is not selected, instead of individual validation.
Thanks
While it's not exactly what you're asking about, may be $pristine is what you want? It's a flag on the form indicating whether the form has ever been edited. If someone typed and then cleared out a field, $pristine would still be false, however.
<form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
<input ng-model="firstName" name="firstName" />
</form>
Then in your controller
.controller('FormController', function($scope){
$scope.doSubmit = function(){
if($scope.myform.$pristine){}
}
})
Alternatively, you can set all your fields to required="true" and use the $valid flag on the form in the same way as described above.
You can use this:
ng-show="!yourfield.length"
Something like this:
<form name="yourform">
<input name="yourfield" ng-model="somefield" ng-minlength="10" required>
<span ng-show="!yourfield.myfield.$error.required">Something</span>
</form>
You should look for Form Validation . Take a look at this tutorial.
<input name="name" class="form-control"
ng-model="user.name" placeholder="Name" required>
<div class="alert alert-danger"
ng-show="userForm.name.$error.required">
Please enter the name.
</div>
The following will show an alert if all fields are empty
angular.module('app', [])
.controller('FormController', function($scope) {
$scope.doSubmit = function(){
if (formIsEmpty($scope.myform)){
alert('You forgot to enter something before submitting');
}
};
function formIsEmpty(form) {
for (var prop in form) {
if (!form.hasOwnProperty(prop)) { continue; }
if (prop[0] === '$') { continue; }
if ($scope[prop]) { return false; }
}
return true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
<input ng-model="firstName" name="firstName" />
<input ng-model="lastName" name="lastName" />
<textarea ng-model="description" name="description"></textarea>
<button type="submit">Submit</button>
</form>
</div>

Validating a form with a dynamic name inside directive

<form name="{{ formname }}" novalidate>
<input type="text" ng-model="first_name" required>
<input type="text" ng-model="last_name" required>
<input type="text" ng-model="email" required>
<span class="error" ng-show="formname.$invalid">Fill in required fields.</span>
<button type="submit"></button>
</form>
I'm trying to validate the form using Angular's built in validation but because the formname is set dynamically by text passed in from the scope I'm not sure how to call it. This attempt above doesn't work.
You can do it with a little help from the controller. Define another variable (f in the example below), watch formname and update f accordingly:
.controller("...", function($scope) {
$scope.first_name = "";
$scope.formname = "fff";
$scope.f = null;
$scope.$watch("formname",function(newval,oldval,scope) {
scope.f = scope[newval];
});
});
See fiddle: http://jsfiddle.net/T7vuD/

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
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
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/
My solution was the following:
$scope.requiredInputsGroup = function () {
var isRequired = true;
if (!$scope.shipment) {
return true;
}
angular.forEach(["userPreference1", "userPreference2", "userPreference3"], function (input) {
if ($scope.shipment[input]) {
isRequired = false;
return false;
}
});
return isRequired;
};
You apply that method to a data-ng-required in each of the inputs...
<form name="myForm" action="#sent" method="post" ng-app>
<input name="userPreference1" type="text" ng-model="shipment.userPreference1" ng-required="requiredInputsGroup()" />
<input name="userPreference2" type="text" ng-model="shipment.userPreference2" ng-required="requiredInputsGroup()" />
<input name="userPreference3" type="text" ng-model="shipment.userPreference3" ng-required="requiredInputsGroup()" />
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
And the last bit I applied was to make the button disabled with a simple myForm.$invalid

Categories

Resources