How reset form and validation after submitting form (AngularJS) - javascript

I want to reset form and all validation messages after submitting a form. Here is plunker:http://plnkr.co/edit/992RP8gemIjgc3KxzLvQ?p=preview
My code is bellow:
Controller:
app.controller('MainCtrl', function($scope) {
$scope.data={fullName:''};
$scope.submit=function(){
console.log('submit')
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.data={fullName:''};
}
});
HTML:
<body ng-controller="MainCtrl">
<form name="myForm" novalidate>
<div>
<label class="control-label">Name</label>
<input
name="full_name"
type="text"
ng-model="data.fullName"
ng-required="true">
<p ng-if="myForm.$submitted && myForm.$invalid">Validation message</p>
</div>
<button ng-click="submit()" type="submit">
Submit
</button>
</form>
</body>
My problem is:
when user enters name in the input and clicks on Submit button, validation message shouldn't be shown, because model, form and validation should be resetted. How I can do it?
I tried to use $setPristine() and $setUntouched(), but it doesn't work for me.
Is it possible to do in AngularJS? Thanks!

I'm surrpised but $setpristine() doesn't update $submitted.
This may not be the prettiest solution but seems to work:
app.controller('MainCtrl', function($scope, $timeout) {
$scope.data = {
fullName: ''
};
$scope.submit = function() {
console.log('submit')
$scope.data = {
fullName: ''
};
$timeout(function() {
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.myForm.$submitted = false;
});
}
});
DEMO

Related

how to validate form using name or id attribute in angular Js

In form I have controls with name,id and class attribute. I cant add any costom attribute in html input element.
In this case how can I apply validation.
Can I write directive on element name or id?
HTML
<form class="form-horizontal text-center" role="form" name="DTOstep1" ng-submit="onSubmit(DTOstep1)" novalidate>
<input name="userinput1" id="userinput1" class="" />
<input name="userinput2" id="userinput2" class="" />
<input name="saveDto" type="submit" class="btn btn-success btn-lg" value="Continue" />
</form>
directive code
(function () {
"use strict";
angular
.module("autoQuote")
.directive('userinput1', [userinput1])
....
Or is there any other way to do form validation. I wan to apply some custom validation to each form field.
The angular way requires the ng-model attribute to each field, in order to bind it with a model property.
function TestCtrl($scope) {
$scope.fields = {
"userinput1" : "Initial Value",
"userinput2" : ""
}
$scope.onSubmit = function onFormSubmit($event, form) {
if(form.$invalid) {
console.log("invalid", form);
event.preventDefault();
return;
}
console.log('valid', form);
//send here
};
}
angular
.module('test', [])
.controller("TestCtrl", ["$scope", TestCtrl])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">
<form name="DTOstep1" ng-submit="onSubmit($event, DTOstep1)">
<input name="userinput1" ng-model="fields.userinput1" required/>
<input name="userinput2" ng-model="fields.userinput2" required />
<input name="saveDto" type="submit" ng-disabled="DTOstep1.$pristine || DTOstep1.$invalid" />
</form>
</article>
</section>
by the way, if you can't edit the view in order to create an angular-form, you need to control the form via dom queries, such as vanilla javascript... using document.querySelector() and checking value property.
UPDATE
Many basic check could be made using simple procedural approach, if you want apply a minlength to the userinput1 field, on each onSubmit you need to check $scope.fields.userinput1.length > ..., et cetera...
A more clean and suggested way is to use html5 validation attributes,
angular decorates them and recognize thei rules, so, you can use min/max/min-length/max-length/required/pattern/disabled etc.
if you want to provide a reusable way, you should have a look at FormController.$addControl or how build a custom directive via attributes that requires ngModelController and so on...
Add required to those fields on which you want to add validation -
'use strict';
var app = angular.module("demo", [], function($httpProvider) {
});
app.controller("demoCtrl", function($scope) {
$scope.onSubmit = function(){
alert('form valid');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demo">
<div ng-controller="demoCtrl">
<form name="form" id="form" class="form-horizontal text-center" role="form" >
<input ng-required="true" ng-model="userinput1" name="userinput1" id="userinput1" class="" /><br>
Check it to make userinput 2 required: <input type="checkbox" ng-model="check" />
<input ng-required="check" ng-model="userinput2" name="userinput2" id="userinput2" class="" />
<br><input ng-click="onSubmit(DTOstep1)" ng-disabled="form.$invalid" name="saveDto" type="submit" class="btn btn-success btn-lg" value="Continue" /><br>
</form>
</div>
</body>
you can also use ng-model inside ng-required to toggle the ng-required true and false.
angular automatically adds classed to each ng-model
This should help
https://docs.angularjs.org/guide/forms
Adding a fiddle as an example
https://jsfiddle.net/x0f6czfk/
<body ng-app="app">
<form ng-controller="mainCtrl">
<input ng-model="name" type="text">
<input ng-model="email" type="text">
<input type="button" ng-click="validateForm()" value="Save">
</form>
</body>
(function(window,document,undefined){
var app = angular.module('app',[]);
app.controller('mainCtrl',function($scope){
var self = this;
$scope.validateForm = function(){
//custom validation
if($scope.name === 'test'){
console.log('wrong name');
return;
}
//custom validation
if($scope.email === 'test#demo.com'){
console.log('wrong email');
return;
}
else{
//if no validation error, submit data;
console.log('valid form');
}
}
});
})(window,document)

angular form submission not checking for validation of form

When I click submit button, the form gets submitted instead of validating for the required fields.
Markup
<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-controller="myCtrl">
<head>
<meta charset="UTF-8">
<title>HTML 5</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
<div id="container">
<p ng-show="msg"> {{ msg }}</p>
<form name="myForm" novalidate ng-submit="valid()">
<p> Name <input type="text" name="name" id="" ng-model="user.name" ng-required=true></p>
<p ng-show="myForm.name.$invalid && myForm.name.$touched">name is required</p>
<p> Email <input type="email" name="email" id="" ng-model="user.email" ng-required=true> </p>
<p ng-show="myForm.email.$invalid && myForm.email.$touched">must be a valid email</p>
<input type="submit" value="submit">
</form>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.valid = function() {
$scope.msg = "form submitted";
}
}]);
</script>
</body>
</html>
Any help would appreciated. Thanks
Shortest way to call function if form is validate is dictated below, which will fired up valid function only when form is valid.
ng-submit="myForm.$valid && valid()"
Or other way would be check myForm object in $scope, because when you give name="myForm" on form, angular does create a object inside scope that have all the information field information inside that object.
$scope.valid = function(){
if($scope.myForm.$valid){
//form is valid
//do $http.post call if you wanted to submit form data
}
else {
alert('form is invalid');//some how notify user that form is invalid.
}
}
You can just disable the submit button using:
ng-disabled="boolean expression"
in your case it will be simply:
<input type="submit" value="submit" ng-disabled="!myForm.$valid">
Try to put:
$scope.valid=function() {
if ($scope.myForm.isValid()) $scope.msg="form submitted";
else $scope.msg="form with errors";
}
hope it helps

Handle form with Angular: error doesn't show

I have simple form. I need to show errors about my fields.
<html lang="en" ng-app="MyApp">
<head></head>
<body ng-controller="AppCtrl">
<form name="myForm" id="myForm">
<input type="text" ng-model="field" name="myField" />
<div ng-show="myForm.myField.$error" style="color: red">
{{myForm.myField.$error}}
</div>
</form>
<script src="bower_components/angular/angular.js"></script>
<script src="controller.js"></script>
</body>
</html>
And this is my controller
angular.module('MyApp',[])
.controller('AppCtrl', function() {
var form = document.getElementById("myForm");
var error = {
myField: 'Error in this field'
};
for (var key in error) {
form[key].$error = error[key];
}
});
Why I can't see error about myField? I get only '{}'
You're not binding the form to AngularJS correctly
<form name="myForm" id="myForm">
This says your form is called myForm, so in your controller you should be using $scope.myForm
No need for var form = document.getElementById("myForm");, just use $scope.myForm in your controller
Try this to see if you access the the form from AngularJS
angular.module('MyApp',[])
.controller('AppCtrl', function($scope) {
$scope.myForm.myField.$error = "just to see it work";
});

Angular's ng-blur on input field not working

Ok, so I'm pretty sure I'm missing something obvious, but I'm not seeing it.
I created a fiddle that I would have thought would throw an alert message when the input box loses focus, but it's not working and I don't know why.
I was expecting an alert message when the user performs the following steps:
click the input box
type something
click somewhere outside of the input box
but these steps do not show an alert message.
Surely, someone knows what I'm doing wrong...?
Here's the code (same as the fiddle):
<div ng-app>
<div ng-controller="MyCtrl">
<form name="myForm">
<input type="text" ng-model="todoText" size="30"
name="myInput" ng-blur="validate(myForm)">
</form>
</div>
</div>
function MyCtrl($scope) {
$scope.validate = function(form) {
alert('blur!');
};
}
It could be your version of angular. Your fiddle is using 1.0.x I updated you to 1.4.x and its working fine:
<div ng-app='myApp'>
<div ng-controller="MyCtrl">
{{santity}}
<form name="myForm">
<input type="text" ng-model="todoText" size="30"
name="myInput" ng-blur="validate(myForm)">
</form>
</div>
</div>
Javascript
angular.module('myApp', []);
angular.module('myApp').controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.santity = 'Hello';
$scope.validate = function(form) {
alert('blur!');
};
}
http://jsfiddle.net/ncapito/LurjLvz7/6/

form is undefined in controller

I have a form...
<form name="userForm" ng-submit="setUsers()">
<input type="number" class="form-control" name="users" ng-model="users.num" required>
<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Continue</button>
</form>
And in my controller I want to see if the form is $pristine...
angular.module('myApp')
.controller('myController', ['$http', '$scope', function($http, $scope) {
$scope.userForm = {};
$scope.users = {};
console.log($scope.userForm) //empty object
console.log($scope.userForm.$pristine); // undefined
console.log($scope.users); //empty object
console.log($scope.users.num); //undefined
}]);
What am I doing incorrectly that I cannot get the form in my controller? I am using AngularJs 1.3
Thanks!
You cannot access form because you are trying to do that before it exist. Please see code example below that can helps you.
var app = angular.module('app',[]);
app.controller('fCtrl', function($scope){
$scope.setForm = function (form) {
$scope.userForm = form;
$scope.users = {};
console.log($scope.userForm) //empty object
console.log($scope.userForm.$pristine); // undefined
console.log($scope.users); //empty object
console.log($scope.users.num); //undefined
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<form name="userForm" ng-submit="setUsers()">
<input type="number" class="form-control" name="users" ng-model="users.num" required>
<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Continue</button>
<span ng-init="setForm(userForm);"></span>
</form>
</div>
</div>
You have to wait for the form to be available. If you access it after the controller has been loaded you will be able to gain access to it.
Test it quickly with something like:
console.log($scope.userForm); // undefined
$scope.logForm= function(){
console.log($scope.userForm); // defined
};
Open your console and see this bin http://jsbin.com/loqic/1/edit?js,output

Categories