how to check all fields are empty in angularjs - javascript

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>

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>

Simple use of the 'required' attribute but also validate the form (to exclude '#')

I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.

Set flag when looping through input fields

I have a series of multiple text fields and a text area. I’m looping through the text fields and the text area and checking if there is a value. If there is not a value I set a flag that says pass=false. Otherwise I set pass=true and would like to fire a custom event if everything evaluates to true. The problem is that because one input field evaluates to true it evaluates them all to true even though two of the fields have no value in them. How would I go about doing this if I wanted it so that all fields have to be filled in but still set pass=false if one or two of them are filled in? Any help is greatly appreciated!
JS Fiddle link: http://jsfiddle.net/YyAjp/12/
HTML:
<form name="headerForm">
<label for="fname">*First Name</label>
<input type="text" class="text" id="fname" name="fname" />
<br/>
<label for="mname">*Middle Name</label>
<input type="text" class="text" id="mname" name="mname" />
<br/>
<label for="fname">*Last Name</label>
<input type="text" class="text" id="lname" name="lname" />
<br/>
<label for="notes">*Notes</label>
<textarea name="notes" /></textarea>
Submit
</form>
JQUERY
$(document).ready(function() {
$("#submit").on('click', function() {
var pass;
$("input,textarea,select").each(function() {
if($(this).val() === ''){
pass = false;
$(this).prev('label').css('color','red');
} else {
pass = true;
$(this).prev('label').css('color','black');
}
});
console.log(pass);
if(pass){ alert('trigger custom event') } else { alert('pass failed'); }
});
});
Change
pass = true;
into
pass = pass && true;
and initialize it to true:
$("#submit").on('click', function() {
var pass = true;
http://jsfiddle.net/mblase75/pgM5X/
(You might also want to use $.trim() on the values first.)

Determining if a form is valid using angular

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

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