I have a form which once submitted, I want to clear all fields and set to it initial state.
I use $scope.form.setPristine(); but field labels keep red color.
How can I avoid this?
EDIT:
Here i post the code. All works fine except by such issue.
Html:
<form name="change_password" novalidate>
<md-input-container style="margin:0;width:200px" flex>
<label>Enter your current password</label>
<input name="password" type="password" ng-model="password" ng-minlength="7" required>
<div ng-messages="change_password.password.$error" ng-if="change_password.password.$dirty" role="alert">
<div class="error_form" ng-message="required">Enter your current password.</div>
<div class="error_form" ng-message="minlength">Password must be at least 7 characters long.</div>
</div>
</md-input-container>
<md-input-container style="margin:0;width:200px" flex>
<label>New Password</label>
<input name="new_password" type="password" ng-model="new_password" ng-minlength="7" required>
<div ng-messages="change_password.new_password.$error" ng-if="change_password.new_password.$dirty" role="alert">
<div class="error_form" ng-message="required">Enter your new password.</div>
<div class="error_form" ng-message="minlength">New password must be at least 7 characters long.</div>
</div>
</md-input-container>
<md-input-container style="margin:0;width:200px" flex>
<label>Confirm new password</label>
<input name="re_new_password" type="password" ng-model="re_new_password" ng-minlength="7" required>
<div ng-messages="change_password.re_new_password.$error" ng-if="change_password.re_new_password.$dirty" role="alert">
<div class="error_form" ng-message="required">Confirm your new password.</div>
<div class="error_form" ng-message="minlength">New password must be at least 7 characters long.</div>
</div>
</md-input-container>
<button class="button" style="width:200px" ng-if="!saving" ng-click="save_password()" ng-disabled="is_uploading || change_password.$invalid || new_password!=re_new_password">Save new password</button>
<div ng-if="saving" layout="row" layout-align="center center">
<md-progress-circular md-mode="indeterminate" size="22"></md-progress-circular>
</div>
</form>
Ctrl:
userService.save_password($scope.password, $scope.new_password).then( function(response) {
$scope.$apply( function() {
if ( response.result ) {
$scope.password = '';
$scope.new_password = '';
$scope.re_new_password = '';
console.info($scope.change_password);
$scope.change_password.$setPristine();
}
showMessage(response);
$scope.saving = false;
})
})
You misunderstand
setPristine();
It only clears classes on your form, nothing else. Variables are still set. You need to do it like below:
$scope.emptyModel = {};
$scope.reset = function() {
$scope.yourFormModel = angular.copy($scope.emptyModel);
$scope.user_form.$setPristine();
$scope.user_form.$setUntouched();
}
Reset with $setPristine and $setUntouched (for your fiddle):
$scope.user_form.$setPristine();
$scope.user_form.$setUntouched();
Related
I am having trouble with form validation in AngularJS. I am trying to show a div based on whether an input is invalid. Angular is putting the correct classes on my inputs (ng-touched and ng-invalid) but it is still keeping the div with a ng-hide class.
form.html
<form id="" name="contactForm"
ng-submit="postForm()" novalidate>
<div class="form-group row">
<label for="full-name" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Name</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="text" placeholder="Jon Doe"
id="full-name" required data-ng-model="formData.name">
</div>
</div>
<!-- This is the only input implemented with the errors -->
<div class="form-group row">
<label for="phone-number" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Phone
Number</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="tel"
placeholder="(630) 555-6723" id="phone-number" required
data-ng-model="formData.phone" name="phone" ng-minlength="10"/>
</div>
<div ng-show="(contactForm.phone.$invalid && contactForm.phone.$touched) || contactForm.phone.$error.minlength">Please enter a valid phone
number.</div>
</div>
<div class="form-group row">
<label for="email" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Email</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="email"
placeholder="jon.doe#gmail.com" id="email" required
data-ng-model="formData.email" />
<div class="invalid-feedback">Please enter a valid email.</div>
</div>
</div>
<div class="form-group row">
<label class="col-2 col-form-label">Contact Method</label>
<div class="col-lg-2 col-md-3 col-xs-4">
<label class="custom-control custom-radio"> <input
id="radio1" name="email" type="radio"
class="custom-control-input" checked="checked"
data-ng-model="formData.pref"> <span
class="custom-control-indicator"></span> <span
class="custom-control-description">Email</span>
</label> <label class="custom-control custom-radio"> <input
id="radio2" name="phone" type="radio"
class="custom-control-input" data-ng-model="formData.pref">
<span class="custom-control-indicator"></span> <span
class="custom-control-description">Phone</span>
</label>
</div>
</div>
<div class="form-group row">
<label for="full-name" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Body</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<textarea rows="15" class="form-control"
placeholder="Type your message here..." id="body-text" required
data-ng-model="formData.body"></textarea>
<div class="invalid-feedback">Please enter a message here.</div>
</div>
</div>
<div class="text-center">
<button ng-disabled="contactForm.$invalid" class="btn-primary btn" type="submit">Submit</button>
</div>
</form>
</div>
angular.js
<!-- SCRIPTS -->
<script>
//form validate
var app = angular.module('contactUs', []);
app.controller('formCtrl', function($scope, $http) {
$scope.formData = {};
$scope.postForm = function() {
$('#loadingScreen').modal('show');
$http({
url : '/api/v1/contact',
method : 'POST',
data : $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function onSuccess() {
console.log("success");
window.scrollTo(0,0);
$('#success-message').show();
}, function onError(){
console.log("error");
window.scrollTo(0,0);
$('#error-message').show();
})
.then(function() {
$('#loadingScreen').modal('hide');
})
}
$scope.formData = {};
});
</script>
Looking at other errors I made sure that the ng-show was using the formName.inputName and that the app and controller were working correctly. The button is disabled correctly when the form is invalid which leads me to believe that the controller and app are not the problem.
I tried using ng-messages which changed my phone portion of the form to
<div class="form-group row">
<label for="phone-number" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Phone
Number</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="tel"
placeholder="(630) 555-6723" id="phone-number" required
data-ng-model="formData.phone" name="phone" ng-minlength="10"/>
</div>
<div ng-messages="contactForm.phone.$error" class="error" ng-if="contactForm.phone.$dirty">
<div ng-message="required">Please enter a phone number we can reach you at.</div>
<div ng-message="pattern">Please enter a valid phone number here.</div>
<div ng-message="minlength">Please enter a phone number that's atleast 10 digits</div>
</div>
</div>
Angular is still adding the correct classes to the input but it is still not displaying. I believe the ng-if is evaluating false. Oddly, when I run
{{contactForm.phone.$dirty}}
in the console it is coming back as undefined
Take a look here and you can see how I got it working. I'll break down the steps below. https://plnkr.co/edit/LJYurBObZsS6ptlVKxvP?p=preview
With the change to using ng-messages, you need to include that module in your app. I wasn't sure if you had made this change or not, but it's straightforward. Include the script for the library, and then update your modules to include ngMessages as a dependency.
var app = angular.module('contactUs', ['ngMessages']);
The second part is fixing a typo. In your html for the contact method area, you have
<label class="custom-control custom-radio">
<input id="radio2" name="phone" type="radio" class="custom-control-input" data-ng-model="formData.pref">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Phone</span>
</label>
You're reusing the name "phone" there, which is going to cause problems since you'll have two different form items with the same name. Probably change those inputs to emailPreference and phonePreference or something to be clear.
As soon as I cleaned that up, it started working. So I think you were all there, just this typo was getting you.
I want to display an error using angularjs, under the "confirm password" input which should say "Passwords don't match".
<form name="settingsForm" ng-submit="vm.login(vm.credentials)" novalidate>
<md-input-container class="md-block" flex-gt-sm="">
<label translate="MY_PROFILE_NEW_PASSWORD"></label>
<input type="password" name="newPassword" id="password"
ng-model="vm.newPassword"
required=""
ng-minlength="8"
md-maxlength="40">
<div ng-messages="settingsForm.newPassword.$error"
role="alert"
multiple="">
<div ng-message="required"
class="my-message"
translate="LOGIN_PASSWORD_INVALID">
</div>
<div ng-message="minlength"
class="my-message"
translate="MIN_8_CHARS">
</div>
</div>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm="">
<label translate="MY_PROFILE_CONFIRM_NEW_PASSWORD"></label>
<input type="password"
name="confirmPassword"
id="confirmPassword"
ng-model="vm.confirmPassword"
required=""
confirm-password="vm.newPassword"
ng-minlength="8"
md-maxlength="40">
<div ng-messages="settingsForm.$error.confirmPassword"
role="alert" multiple="" >
<div ng-message="required"
class="my-message"
translate="LOGIN_PASSWORD_INVALID">
</div>
<div ng-message="minlength"
class="my-message"
translate="MIN_8_CHARS">
</div>
</div>
<div ng-message="required"
class="my-message"
translate="LOGIN_PASSWORD_INVALID">
</div>
<div ng-message="confirm-password"
class="my-message">
Passwords don't match.
</div>
</md-input-container>
<md-button class="md-raised md-primary btn-auth"
type="submit"
ng-disabled="settingsForm.$invalid"
translate="SUBMIT"
ng-click="vm.changePassword(vm)">
</md-button>
I need to make this form display error messages for each particular case.
I haven't found how "confirm-password" attribute should work for validation.
You have to create a Custom Directive. Try this.
<div data-ng-controller="PasswordController as vmPassword">
<form name="passwordForm">
<md-input-container class="md-block" flex-gt-sm>
<label>Password</label>
<input type="password"
name="password"
ng-model="vmPassword.password"
required
/>
<div ng-messages="passwordForm.password.$error" role="alert" class="form-errors first-name-error">
<div ng-message="required">Password is required.</div>
</div>
</md-input-container>
<md-input-container class="md-block" flex-gt-sm>
<label>Confirm Password</label>
<input type="password"
name="confirm_password"
ng-model="vmPassword.confirm_password"
required
compare-to="vmPassword.password"
/>
<div ng-messages="passwordForm.confirm_password.$error" role="alert" class="form-errors first-name-error">
<div ng-message="required">Password is required.</div>
<div ng-message="compareTo">Passwords do not match</div>
</div>
</md-input-container>
</form>
</div>
Custom Directive
(function () {
"use strict";
angular.module('app').directive('compareTo', compareTo);
compareTo.$inject = [];
function compareTo() {
return {
require: "ngModel",
scope: {
compareTolValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.compareTolValue;
};
scope.$watch("compareTolValue", function() {
ngModel.$validate();
});
}
};
}
})();
Goodluck .! :)
Demo here - http://embed.plnkr.co/UK4G4Lm5BCNNe5SWoA9r/
i know have many result in this question but no one give work answer for me.
html 1:
<button class="basebtn logbtn" ng-click="openlog()">LOGIN</button>
<button class="basebtn regbtn" ng-click="openreg()">SIGN UP</button>
html 2:
<div ng-controller="main">
<center><img class="img-login" ng-src="../images/form-logo.png"/></center>
<form class="login" name="log" ng-submit="login()" novalidate>
<div class="form-group login-form" ng-class="{'has-error' : isInvalid(log.email) ,'has-success' : isValid(log.email)}">
<input type="email" class="form-control" name="email" ng-model="user.email" required placeholder="Email">
<div class="alert alert-danger" role="alert" ng-show="isInvalid(log.email)">Enter valid email</div>
</div>
<div class="form-group login-form" ng-class="{'has-error' : isInvalid(log.password) ,'has-success' : isValid(log.password)}">
<input type="password" class="form-control" name="password" ng-model="user.password" required placeholder="Password">
<div class="alert alert-danger" role="alert" ng-show="isInvalid(log.password)">This Feild is required</div>
</div>
<div class="form-group" style="text-align:center;">
<input type="submit" class="logbnt" value="LOGIN" ng-disabled="! log.$valid" data-dismiss='modal'/>
</div>
</form>
angular :
$scope.login = function(){
$http.post("www.example.com/login",$scope.user).then(function(res){
localStorage.setItem("token",res.data.token);
//how i close the modal ???
});
}
//here create the modal
$scope.openlog = function () {
$scope.$modalInstance = $uibModal.open({
templateUrl:"login.html",
});
}
that my code , how i close in $http result the modal ?
You can do this,
$scope.login = function(){
$http.post("www.example.com/login",$scope.user).then(function(res){
localStorage.setItem("token",res.data.token);
$modalInstance.dismiss('cancel');
});
};
I want to show the required error message once the from is submitted but not sure how to do it i am trying as shown below
<div class="controls">
<form name="formx" >
<ul class="form small">
<div class="tag">ID</div>
<input type="text" class="small" name="enrolmentId" ng-model="enrolmentDetail.Id" required="" onkeypress='return !(event.charCode == 32 )'>
<div class="error text-danger" style="position: absolute;margin-left: 120px;" ng-show="formx.enrolmentId.$error.required && (formx.$submitted || formx.enrolmentId.$touched)"><p>Id is required</p></div>
</li>
<li>
<div class="btn" ng-click="saveDetails(enrolmentDetail)" ng-show="formAction=='save'">SAVE</div>
</li>
</ul>
</form>
</div>
here now the error message is shown once we dirty the textbox but i want to show the error message once the form is submitted and if there is required error from should not be submitted
trying used ng-submit but not sure how to do it
Please help by creating a fiddle or posting a example to do it
This is an example
html
<body ng-app="myApp">
<div ng-controller="myCtrl as mc">
<form class="form" name="myForm" ng-submit="mc.submit(myForm)" novalidate>
<div class="form-group">
<label for="username">Username</label>
<input name="username" class="form-control" type="text" ng-model="mc.username" required/>
<p class="text-danger" ng-show="myForm.username.$error.required && mc.submitted">Username is required</p>
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" class="form-control" type="password" ng-model="mc.password" required/>
<p class="text-danger" ng-show="myForm.password.$error.required && mc.submitted">Password is required</p>
</div>
<button class="btn btn-success">submit</button>
</form>
<p class="text-success" ng-show="mc.sent && mc.submitted">Form sent</p>
js
angular.module("myApp",[])
.controller("myCtrl", function(){
var vm = this;
vm.submit = submit;
function submit(form){
vm.submitted = true;
if(form.$valid && vm.submitted === true){
//Send data logic
vm.sent = true;
}
}
I am unable to get automatic radio button checked when I edit the User From using following Html and AngularJs Code. When I console {{changeUser}} this returns following data
{"id":1,"username":"Ramesh","password":"Ramesh1#23","role":"admin","active":"no"}. When I load the edit form I have to automatically checked the no radio button in the following code.
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal form-bordered" name="editUserForm" data-ng-submit="userEdit(changeUser)">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Username*</label>
<div class="col-md-4">
<input class="form-control" type="text" name="userName" data-ng-model="changeUser.username" value="{{ changeUser.username }}" data-ng-pattern="/^[a-z0-9_ .-]{5,15}$/i" required />
<span style="color:red" class="error" data-ng-show="editUserForm.userName.$error.pattern" >Only letters, integers, and underscores.Minimum 5 characters to maximum 15 characters.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Password*</label>
<div class="col-md-4">
<input class="form-control" type="password" name="changePassword" data-ng-model="changeUser.password" value="{{ changeUser.password}}" data-ng-pattern="usersPattern.password" required />
<span style="color:red" class="error" data-ng-show="editUserForm.changePassword.$error.pattern">Minimum of 8 characters, 1 capital letter,1 lowercase, 1 special-case and 1 numeric.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Action</label>
<div class="col-md-4">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changeUser.active" value="yes"/>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changerUser.active" value="no"/>
No
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn purple" data-ng-disabled= "editUserForm.$invalid">
<i class="fa fa-check"></i> Edit</button>
<button type="button" class="btn red" data-ng-click="cancelEdit()">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
The Controller is
(function (){
"use strict";
function UsersEditController($scope, UserFactory, $http, $location) {
$scope.$on('$viewContentLoaded', function () {
App.initAjax(); // initialize core components
});
$scope.changeUser = {};
$scope.changeUser = UserFactory.get();
$scope.userEdit = function(data) {
$scope.changeUser = data;
console.log($scope.changeUser);
};
$scope.usersPattern = {
password: '((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%]).{8,20})'
};
$scope.cancelEdit = function() {
$location.path('users');
};
}
UsersEditController.$inject = ['$scope', 'UserFactory', '$http', '$location'];
angular.module('books').controller('UsersEditController', UsersEditController);
})()
And I guess this is your answer (even without js code provided :) )
https://stackoverflow.com/a/18446612/552194
You need to add ng-value and use it instead of the standard value