AngularJS and Bootstrap: Red border on invalid input field on submit - angularjs

I've this basic form implemented using AngularJS and Bootstrap:
http://jsfiddle.net/dennismadsen/0stwd03k/
HTML
<div ng-controller="MyCtrl">
<form class="well" name="formTest" ng-submit="save()">
<div class="form-group">
<label for="name">Name*</label>
<input type="name" class="form-control" id="name" placeholder="Enter name" required />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
JavaScript
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.save = function () {
};
}
Result
The Name input field is required. When I click the submit button, I need the input field to have a red border if it's invalid. How can this be done?
Alternatively, if I unfocus the input field and it's still not valid, it would be great that the red corder is shown on that time, instead of waiting for the form submit.

Twitter Bootstrap has an has-error class, so I would use this in conjunction with ng-class for the form group, then a label with the label and label-danger classes for good measure:
<div class="form-group" ng-class="{'has-error': errors.Name }">
<label for="name">Name*</label>
<input type="name" class="form-control" id="name" placeholder="Enter name" required />
<span class="label label-danger" ng-if="errors.Name">{{errors.Name}}</span>
</div>
Then in your controller, have an errors object, and set the Name property of this to a string when the name is invalid.

The first thing you were missing was adding ng-model='name' to input field, then only will the form become invalid once you click submit, otherwise the form will always be valid since it considers that there is no field present.
Then I'd add the submitted class on the submit click button, then put the border css like .submitted would be the parent and .ng-invalid would be the child so we can put the style on .submitted .ng-invalid
HTML
<div ng-controller="MyCtrl">
<form class="well" name="formTest" ng-class="{'submitted': submitted}" ng-submit="save()" >
<div class="form-group">
<label for="name">Name*</label>
<input type="name" class="form-control" id="name" placeholder="Enter name" ng-model="name" required />
</div>{{submitted}}
<button type="submit" class="btn btn-default" ng-click="submitted= true;">Submit</button>
</form>
</div>
CSS
.submitted .ng-invalid{
border: 1px solid red;
}
Working Fiddle
Hope this could help you, Thanks.

Basically you need angular to take over validation, so add novalidate to form. Also add ng-class to input field to determine wether to add error css
<form name="myForm" novalidate ng-submit="test()">
<input type="text" name="user" ng-model="user" required ng-class="myForm.user.$invalid && myForm.user.$dirty ? 'error' : ''">
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required. </span>
</span>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
Good luck..

Related

Cannot disable submit button by $invalid while page load

I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.
<div id="reg_bground">
<div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
<form name="myForm" novalidate>
<div style="font-family:calibri; font-size:30px; font-weight:bolder;">
<span>Register:</span>
</div>
<div>
<span>Name:</span><br>
<input type="text" name="user" ng-model="user" required><br>
<p ng-show="myForm.user.$dirty && myForm.user.$invalid">*Please insert the name</p>
</div>
<input type="number">
<input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
</form>
</div>
</div>
You essentially check for $dirty state in the submit button for disabled status.
<input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
$dirty is only set to true when user has meddled with the myForm.user input, which is not the case on page load. Instead, try checking the $pristine state (or !$dirty)
<input type="submit" ng-disabled="myForm.user.$pristine || myForm.user.$invalid">
Delete the dirty check in the submit button:
<input type="submit" ng-disabled=" ̶m̶y̶F̶o̶r̶m̶.̶u̶s̶e̶r̶.̶$̶d̶i̶r̶t̶y̶ ̶&̶&̶ ̶ myForm.user.$invalid">
The field content is valid
$invalid working when you enter a input and input doesn't match your pattern .
you must use $error.required for your goal.
follwing will work
<div id="reg_bground">
<div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
<form name="myForm" novalidate>
<div style="font-family:calibri; font-size:30px; font-
weight:bolder;">
<span>Register:</span>
</div>
<div>
<span>Name:</span><br>
<input type="text" name="user" ng-model="user" required><br>
<p ng-show="myForm.user.$dirty &&
myForm.user.$error.required">*Please insert the name</p>
</div>
<input type="number">
<input type="submit" ng-disabled="myForm.user.$dirty &&
myForm.user.$error.required">
</form>
</div>

Resting Form and Clear Error Validations in register form on clicking a button

I am doing one register page using angularjs.
Follows my html code:
<form name="frominline" action="post" class="clearfix form-hidden" id="Register-form">
<div class="col-md-12">
<div class="input-group blmd-form">
<div class="blmd-line">
<input type="text" name="userid" autocomplete="off" id="username" class="form-control" required autofocus="" ng-model="user.name" ng-minlength="3" ng-maxlength="12" ng-model-options="{ allowInvalid: true }">
<label class="blmd-label">User Id</label>
</div>
<p class="login-error" ng-show="frominline.userid.$dirty && frominline.userid.$error.required">
<span style="color : red">required</span>
</p>
<p ng-show="frominline.userid.$error.minlength" class="help-block" style="color:red;">Username is too short.</p>
<p ng-show="frominline.userid.$error.maxlength" class="help-block" style="color:red;">Username is too long.</p>
</div>
<div class="input-group blmd-form">
<div class="blmd-line">
<input type="email" name="email" autocomplete="off" id="email" class="form-control" required autofocus="" ng-model="user.email">
<label class="blmd-label">Email</label>
</div>
<span class="login-error" ng-show="frominline.email.$error.required && frominline.email.$dirty" style="color:red;" ng-model-options="{ allowInvalid: true }">required</span>
<span class="login-error" ng-show="!frominline.email.$error.required && frominline.email.$error.email && frominline.email.$dirty" style="color:red;">invalid email</span>
</div>
<button type="reset" ng-click="resetform(frominline)">reset</button>
</form>
My js code:
app.controller('loginCtrl'['$scope',function('$scope'){
var user = this;
$scope.resetform(form){
user.name='';
user.email='';
$scope.frominline.$dirty = false;
$scope.frominline.$pristine = true;
$scope.frominline.$submitted = false;
}]);
Now, in first image, those are the validation errors.
Now, I hit the reset button and the validation errors are gone but in the second image I got required field.
Can you please help me removing or reseting the whole form on a button click?
I tried with many options like $setPristine() or $setValidity() but i can't fix this issue "required" error message.
Follows the image of the form with only required error message after clicking reset button:
The form is probably cleared, but those input fields are not. When you are display the error for a particular field (e.g. ng-show="frominline.userid.$error.minlength") include the state of the form as well (e.g. ng-show="frominline.$submitted && frominline.userid.$error.minlength").

validating controls inside different div in AngularJs

I am using AngularJs. I have 2 div, which I am hiding and showing each other. Each div contains few controls, which I have set "required" validation on click of submit button. By default the div "createMenu" is shown. Below is the code used:
<div ng-controller="testController" ng-init="init()">
<form name="mainForm" id="createForm" ng-submit="mainForm.$valid && add()" novalidate="">
<div class="container" ng-show="createMenu">
<div class="row">
<div class="col-sm-2">
<label>Name :</label>
</div>
<div class="col-md-6 form-group">
<input type="text" maxlength="150" required="" ng- model="testName" name="testName" />
</div>
</div>
<span style="color:red" ng-show="submitted == true && mainForm.testName.$error.required">Name is required</span>
<br />
<input type="submit" value="Submit" ng-click="submitted=true" />
</div>
<div class="container" ng-show="copyView">
<div class="row">
<div class="col-sm-4">
<label class="control-label">New Name :</label>
</div>
<div class="col-sm-4">
<input type="text" required="" maxlength="150" class="form-control" ng-model="NewName" name="NewName" />
</div>
</div>
<span style="color:red" ng-show="submitted == true && mainForm.NewName.$error.required">New Name is required</span>
<input type="submit" value="Submit" ng-click="copydata()" />
</div>
The issue is: If I click on the submit button in the first div, the controls in the div "copyView" is also getting validated. When the first submit button is clicked, I want to validate the textbox available in the "createMenu" div only. when the "copyView" div is shown, than at that time, when the submit button inside that div is clicked, the "New Name" textbox should be validated.
How to differentiate between the two divs, when the error messages are shown.
Thanks
You can use separate form tag for the separate div tag.
like
<div ng-controller="name">
<form>
//first dive
</form>
<form>
//second div
</form>
</div>

validate form on button in angularjs

I have to validate a form only after click on button. Now it is working on blur and focus. How can I disable focus and blur validation and validate them on button click. fiddle
<form ng-app="form-example" class="row form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="email" id="inputEmail" placeholder="Email" ng-model="email" required>
<div class="input-help">
<h4>Invalid Email</h4>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input ng-model="password" class="immediate-help" required type="password" id="inputPassword" placeholder="Password">
<div class="input-help">
<ul>
<li>required</strong></li>
</ul>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn">Create Account</button>
</div>
</div>
</form>
You could have dummy class on your form level that will tell the form has been submitted or not like ng-class="{submitted: submitted}", and on click of button we will use ng-click="submitted=true" so that after clicking on button form will have submitted class on it. Then we will apply our CSS rule for ng-invalid & ng-dirty to also consider an .submitted class by using concept of deep nesting of classes.
/* Show red border when stuff has been typed in, but its invalid */
.submitted .ng-dirty.ng-invalid {
border-color:#ec3f41;
}
Other CSS rules should be taken care of this thing like I shown above.
the problem is that you just added the validation and you're showing the message on ng-invalid ( with css). here is an example of working code to do what you want.
<div class="form-group col-xs-12 required" ng-class="{ 'has-error' : creditCardDetailsForm.security_code.$invalid && submitted}">
<label class="col-lg-28 col-l-5 col-md-5 text-left font-l-20 primary control-label">Security code (CVC) </label>
<div class="col-lg-3 col-md-4 text-left">
<input class="form-control" name="security_code" data-stripe="cvc" ng-model="payment_details.security_code" type="number" minLength="3" required>
<p ng-show="creditCardDetailsForm.security_code.$invalid && submitted" class="help-block">Security code is required.</p>
<p ng-show="creditCardDetailsForm.security_code.minLength.$invalid && submitted" class="help-block">Invalid CVC.</p>
</div>
</div>
see, here I check if the form is invalid and the submitted has been clicked...
in my controller:
$scope.purchasePackage = function (status, response) {
$scope.submitted = true;
if ($scope.creditCardForm.creditCardDetailsForm.$valid) {
//do something
}
};
since you did your hide and show with CSS you can just add the class on click to the form and then do .submitted .ng-invalid so it only shows up after you have submitted.

AngularJS validation show validation msg on submit [duplicate]

This question already has answers here:
show validation error messages on submit in angularjs
(13 answers)
Closed 7 years ago.
I am dynamically adding fields and want "required" validation on each field I add.
Problem is angular validates these fields before i submit.
<form name="outerForm">
<div ng-repeat="item in items">
<data-ng-form name="innerForm">
<input type="text" placeholder="{{item.questionPlaceholder}}" name="fieldU" ng-model="item.question" required>
<span class="error" ng-show="innerForm.fieldU.$error.required">
Required!
</span>
<input type="text" name="userName" placeholder="enter text..." ng-model="item.text" required>
<span class="error" ng-show="innerForm.userName.$error.required">
Required!
</span>
</data-ng-form>
</div>
<input type="submit" ng-click="save(items)" ng-disabled="outerForm.$invalid" />
<button ng-click="add()">New Field</button>
</form>
here is fiddle
https://jsfiddle.net/Lbw6ow8k/7/
I want required msg only to show when user did not add anything to text box and after he/she clicked submit
I'd love to maintain one scope variable which will keep a track that form is submitted or not
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<form name="outerForm" ng-init="submitted=false" novalidate="">
<div ng-repeat="item in items">
<data-ng-form name="innerForm">
<input type="text" placeholder="{{item.questionPlaceholder}}" name="fieldU" ng-model="item.question" required/>
<span class="error" ng-show="$parent.submitted&& innerForm.fieldU.$error.required">
Required!
</span>
<input type="text" name="userName" placeholder="enter text..." ng-model="item.text" required/>
<span class="error" ng-show="$parent.submitted && innerForm.userName.$error.required">
Required!
</span>
</data-ng-form>
</div>
<input type="submit" ng-click="submitted=true;save(items)" ng-disabled="submitted && outerForm.$invalid" />
<button ng-click="add()">New Field</button>
</form>
Items: {{items}}
</div>
Working Fiddle
You can create a $scope.isSubmit variable to detect whether the form has submitted or not:
Controller:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.save = function (question) {
$scope.isSubmit = true; // Will be true if the form has submitted
console.log(question)
}
$scope.items = [];
$scope.add = function () {
if ($scope.items.length >= 10) {
toastr.warning("Only 10 fields are allowed");
} else {
$scope.items.push({
//inlineChecked: false,
question: "",
questionPlaceholder: "foo",
text: ""
});
}
};
});
View:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="outerForm" novalidate>
<div ng-repeat="item in items">
<data-ng-form name="innerForm">
<input type="text" placeholder="{{item.questionPlaceholder}}" name="fieldU" ng-model="item.question" required> <span class="error" ng-show="innerForm.fieldU.$error.required && isSubmit">
Required!
</span>
<input type="text" name="userName" placeholder="enter text..." ng-model="item.text" required> <span class="error" ng-show="innerForm.userName.$error.required && isSubmit">
Required!
</span>
</data-ng-form>
</div>
<input type="submit" ng-click="save(items)" />
<button ng-click="add()">New Field</button>
</form>Items: {{items}}</div>
So, I deleted the ng-disable in the button in order to make the submit button clickable even though the form isn't correct. Moreover, you should add novalidate into the form tag to disable the default form validation from HTML5.
Here is the full source code on JsFiddle.

Resources