Is there a way to reset the $touched in Angular? - angularjs

I'm trying to implement a "Reset" button for my form. Some of my text fields use the $touched to determine if an error is displayed. But once the $touched flag is set, when I reset the model, $touched is not reset and so my error messages remain visible.
<div class="col-sm-4" ng-class="{'has-error' : donationForm.firstName.$invalid && donationForm.firstName.$touched}">
<label for="firstName" class="control-label">First Name</label>
<input type="text" id="firstName" name="firstName" class="form-control"
ng-model="editableDonation.person.firstName" ng-required="true" ng-maxlength="20" />
<span class="help-block" ng-show="donationForm.firstName.$error.required && donationForm.firstName.$touched">
First Name is required.
</span>
<span class="help-block" ng-show="donationForm.firstName.$error.maxlength">
First Name is too long (20 max).
</span>
</div>
Is there a way to do that?
My resetForm:
$scope.resetForm = function () {
$scope.donationForm.$setPristine();
$scope.model = '';
$scope.donation = donationService.defaultDonation;
$scope.editableDonation = angular.copy($scope.donation);
};
http://plnkr.co/edit/Oa91ZkTatsddSA4oujQK

DeborahK89 helped me by pointing out that I could use:
$scope.donationForm.$setUntouched();

Related

Clear form input field after submit in Angularjs with php..? [duplicate]

This question already has answers here:
Resetting form after submit in Angularjs
(5 answers)
Closed 4 years ago.
When i am click add button for add records in next time then last form data is present in form it is not clear in bootstrap form model.
$scope.saveAdd = function () {
$http({
method: 'post',
url: 'user/insert',
data: $scope.form,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data)
{
if (data == 1) {
$scope.user_succ = $scope.user_succ ? false : true;
$scope.succ = "User added successfully";
$timeout(function () {
$(".modal").modal("hide");
}, 3000);
} else if(data == 3) {
$scope.confirm_password=$scope.confirm_password ? false :true;
$scope.confirm_password_error="Confirm Password is Not Matched";
}else{
$scope.user_err = $scope.user_err ? false : true;
$scope.err = "User insertion failed! Try again.";
}
});
};
My View page:-
This is my view page that is load from angularjs routes.js.If you found any error error please give me some feedback.or any others angularjs validation you have please share with me.
<form method="POST" name="addItem" role="form" ng-submit="saveAdd()">
<div class="modal-body">
<div class="form-group">
<label for="name" class="col-form-label">Name<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="form.name" id="name" name="name" placeholder="Enter Name" required>
<span style="color:red" ng-show="addItem.name.$touched && addItem.name.$invalid">Please Enter User Name.</span>
</div>
<div class="form-group">
<label for="phone" class="col-form-label">Phone Number<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="form.phone" id="phone" name="phone" placeholder="Enter Phone Number" required="">
<span style="color:red" ng-show="addItem.phone.$touched && addItem.phone.$invalid">Please Enter Phone Number.</span>
</div>
<div class="form-group">
<label for="usertype" class="col-form-label">User Type<span class="text-danger">*</span></label>
<select class="form-control" ng-model="form.type" id="type" name="type" required="">
<option value="">Select a user type</option>
<option value="branch">Branch Admin</option>
<option value="manager">Branch Manager</option>
</select>
<span style="color:red" ng-show="addItem.type.$touched && addItem.type.$invalid">Select User Type.</span>
</div>
<div class="form-group">
<label for="address" class="col-form-label">Address</label>
<textarea class="form-control" ng-model="form.address" id="address" name="address" placeholder="Enter Address" required=""></textarea>
<span style="color:red" ng-show="addItem.address.$touched && addItem.address.$invalid">Please Enter Address.</span>
</div>
<div class="form-group">
<label for="username" class="col-form-label">Username<span class="text-danger">*</span></label>
<input type="text" class="form-control" ng-model="form.username" id="username" name="username" placeholder="Enter Username" required="">
<span style="color:red" ng-show="addItem.username.$touched && addItem.username.$invalid">Please Enter Username.</span>
</div>
<div class="form-group">
<label for="password" class="col-form-label">Password<span class="text-danger">*</span></label>
<input type="password" class="form-control" ng-model="form.password" placeholder="Password" name="password" required="required" ng-minlength="6"/>
<div ng-if="addItem.password.$touched || signupSubmitted">
<p style="color:red" ng-show="addItem.password.$error.required" class="help-block">Password is required</p>
<p style="color:red" ng-show="addItem.password.$error.minlength" class="help-block">Minimum 6 character</p>
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Confirm Password<span class="text-danger">*</span></label>
<input type="password" class="form-control" name="confirm_password" ng-model="form.confirm_password" placeholder="Confirm password" match-password="password" required>
<div ng-if="addItem.confirm_password.$touched || signupSubmitted">
<p style="color:red" ng-show="addItem.confirm_password.$error.required" class="help-block">Confirm password is required</p>
<p style="color:red" ng-show="confirm_password" >{{confirm_password_error}}</p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" >Submit</button>
</div>
</form>`
You can try reset function which reset your form fields. But this is not the accurate solution. Please provide your Complete controller and HTML code to make an accurate solution.
$scope.resetForm = function(){
/* reset the data to a new object so that all the properties
* of form are reset
*/
$scope.data = {};
};
UPDATE
Based on the partial HTML code, you can try form controller API setPristine: $scope.FORMNAME.$setPristine();
Replace FORMNAME with your form name. Also make note that as your form is binding a model object to your inputs so, you need to take care of clearing those input model as well:
$scope.formData = {};
Hope this will help to solve your point :)
The reason is that your previous value that you bind with model is still there. So, you can do either of 2 things:
Inject $route in controller and do $route.reload() on ng-submit and the route is reloaded.
Reinitialize the model by creating and calling a function which clears the data.Use $scope.formName.$setPristine() if you have validation depending on this pristine state of form
NOTE: $route.reload() will reload your route, so all the changes which have in your controller will be reverted. So choose accordingly.
Its Work.With Minor Change.
$scope.form = {}; // clears input fields
$scope.NameofFormSubmitted.$setPristine();
$scope.NameofFormSubmitted.$setUntouched();
I think what you are looking for is:
$scope.form = {}; // clears input fields
$scope.NameofFormSubmitted.$setPristine();
$scope.NameofFormSubmitted.$setUntouched(); // resets touch events

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").

AngularJS show error when submitting

I am using AngularJS step wizard and inside the form for the first step I need validation errors to appear when the use tries to hit submit. Right now I have the following:
<span class="error" ng-show="user.validate.step1.firstname.$invalid">Required Field</span>
But the error shows when I first goto the step and when I start typing in the field it goes away, I would like this to appear when the user tries to hit submit, not when they first goto the step. I already have this to indicate a required field
<span class="error">*</span>
Here is the full code:
<form name="user.validate.step1" novalidate>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="firstname" class="col-md-4 form-label">First Name:</label>
<div class="col-md-8">
<div class="input-group">
<input class="form-control" type="text" name="firstname" ng-model="user.firstname" value="{{user.firstname}}" ng-blur="blur1=true" required />
<span class="error" ng-show="user.validate.step1.firstname.$invalid">*</span>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
keep in mind I have more than one input in this form.
Add the validation in the button using ng-click="validateInputs()" and create a var invalidEntry and a function validateInputs() to check if the input is valid or not. Something like this:
var inputs = [inputModel1,inputModel2,inputModel3];
function validateInputs(){
invalidEntry = false;
for(e in inputs){
if(CheckInvalid(inputs[e])){
invalidEntry = true;
return;
}
}
}
function CheckValid(string){
if(string == "" || string === null || string === undefined){
return true;
} else {
return false;
}
}
The submit button:
<button ng-click="validateInputs()">Submit</button>
And the span:
<span class="error" ng-show="invalidEntry">Required Field</span>
And the inputs should look like this:
<input type="text" ng-model="inputModel1"></input>
<input type="text" ng-model="inputModel2"></input>
<input type="text" ng-model="inputModel3"></input>
You should change ngShow in following way
ng-show="user.validate.step1.firstname.$invalid && !user.validate.step1.firstname.$pristine"
Check this article block AngularJS Form Validation: Only Showing Errors After Submitting the Form

Cannot clear form

I am trying to reset the form after the submit button is clicked. I understand that setting the form to pristine alone should not clear the input fields. I tried implementing the various suggestions to clear form by setting the form to pristine and then assigning null to all input fields. Is there a more neat way to implement it ?
Template:
<p>{{contactForm.$pristine}}</p>
<div class="inBox">
<form name="contactForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<label>Name</label>
<input type="text" ng-model="tabVm.name" class="form-control" name="name" required>
<p ng-show="contactForm.name.$invalid && !contactForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.email.$invalid && !contactForm.email.$pristine }">
<label>Email</label>
<input type="email" ng-model="tabVm.email" name="email" class="form-control" required>
<p ng-show="contactForm.email.$invalid && !contactForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>
<div class="form-group">
<label>Contact Number</label>
<input type="tel" ng-model="tabVm.number" class="form-control">
</div>
<div class="form-group" ng-class="{ 'has-error' : contactForm.message.$invalid && !contactForm.message.$pristine }">
<label>Message</label>
<textarea type="text" rows="5" ng-model="tabVm.message" name="message" class="form-control textBox" required></textarea>
<p ng-show="contactForm.message.$invalid && !contactForm.message.$pristine" class="help-block">Brief message is required.</p>
</div>
</form>
<button type="submit" ng-click="sendMsg()" class="btn large-btn"
ng-disabled="contactForm.message.$invalid || contactForm.name.$invalid||contactForm.email.$invalid " >Send</button>
</div>
app.js
$scope.contactForm.$setPristine();
and I also tried
$scope.contactForm.$pristine=true;
Neither of them seem to work. I use angular 1.4.8.
Thank you.
You should use $setPristine() and then reset the ng-model object. Also pay attention you have the submit button outside the <form>.
This is a working JSFiddle (I used only one input for example)
$scope.sendMsg = function() {
$scope.contactForm.$setPristine();
$scope.tabVm = {};
}
You referenced controlForm, but the html you posted have contactForm
I finally got it working by making the following changes :
<div class="container box col-lg-6" >
<p>{{contactForm.$pristine}}</p>
<p>name state: {{contactForm.name.$pristine}}</p>
<div class="inBox">
<form name="contactForm" ng-submit="sendMsg(contactForm)" novalidate>
<div class="form-group" ng-class="{ 'has-error' : contactForm.name.$invalid && !contactForm.name.$pristine }">
<label>Name</label>
<input type="text" ng-model="tabVm.name" class="form-control" name="name" required>
<p ng-show="contactForm.name.$invalid && !contactForm.name.$pristine" class="help-block">You name is required.</p>
</div>
<input type="submit" class="btn large-btn"
ng-disabled="contactForm.message.$invalid || contactForm.name.$invalid||contactForm.email.$invalid " >
</form>
</div>
</div>
and app.js :
$scope.sendMsg=function(form){
if(form.$valid){
console.log("Form is valid"); //this was a check I used to confirm that the controller recognized the form.
}
form.$setPristine();
tabVm.name="";
}
}
I do not clearly understand why this works or what was I doing wrong earlier. I would appreciate if anyone could explain. Thank you.
Do as follows
$scope.sendMsg = function(){
//your function code
$scope.tabVm={};
$scope.tabVm.name='';
$scope.tabVm.email='';
$scope.tabVm.number='';
$scope.tabVm.message='';
}

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

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..

Resources