AngularJs radio button dirty validation not working - javascript

I have two fields , for email the validation is working fine , but for radio button no error is been shown .. i am not getting this , why this is happening . i ma using angular-1.0.8.min.js
//js code
var app = angular.module("App", []);
app.controller('signupController', ['$scope', function($scope) {
$scope.selectedGender = '';
$scope.gender = [{'name':'Male', 'id':1}, {'name':'Female', 'id':2}];
$scope.submitted = true;
$scope.signupForm = function() {
if ($scope.signup_form.$valid) {
// Submit as normal
} else {
$scope.signup_form.submitted = true;
}
}
}]);
//html code
<!DOCTYPE html>
<html >
<meta charset="utf-8">
<meta content="width=device-width" name="viewport">
<body ng-app="validationExampleApp">
<div align="center" style="width: 500px; ">
<form ng-controller="signupController" name="signup_form" novalidate ng-submit="signupForm()">
<fieldset>
<legend>Signup</legend>
<div class="row">
<div class="large-12 columns">
<label>Your email</label>
<input type="email"
placeholder="Email"
name="email"
ng-model="signup.email"
ng-minlength=3 ng-maxlength=20 required />
<div class="error"
ng-show="signup_form.email.$dirty && signup_form.email.$invalid && signup_form.submitted ">
<small class="error"
ng-show="signup_form.email.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="signup_form.email.$error.email">
That is not a valid email. Please input a valid email.
</small>
</div>
</div>
</div>
<div ng-repeat="(key, val) in gender">
<input type="radio" ng-model="signup.selectedGender" name="radiob" id="{{val.id}}" value="{{val.id}}" ng-click required /> {{val.name}}
</div>
<div class="error"
ng-show="signup_form.radiob.$dirty && signup_form.radiob.$invalid && signup_form.submitted ">
<small class="error" ng-show="signup_form.radiob.$error.required">
Your email is required.
</small>
</div>
<button type="submit" class="button radius">Submit</button>
</fieldset>
</form>
</div>
</body></html>

It's hard to tell for sure because the code provided is invalid but you are probably hitting the angular js bug where it doesn't mark the radio button as valid until all radio buttons have been selected.
See this question
This is fixed in version 1.2.0-rc.3. I've created a Plunker demo here with some code changes to mimic what I think you are trying to do.

Related

how can i do select options required & Email validation in angular js?

when clicked on submit button, it will call function, in that function i am trying to write logic to disable submit button when fields are not valid, here email must be contain #, dot and after dot minimum 2 & maximum 4 alphabet characters. I tried bellow code.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
<div>
<select id="country" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)"
ng-required>
<option ng-repeat="(key,country) in countries" value="{{key}}">{{country[0]}}</option>
</select>
</div>
<div>
<select id="state" ng-disabled="!states[state1].length" ng-model="cities" ng-required>
<option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
</select>
</div>
<input type="email" ng-disable="myForm.user.email.$valid" ng-model="user.email" name="eamil" ng-required/>
<button ng-disable="myForm.user.email.$valid" ng-click="formsubmit();">submit</button>
</form>
</div>
SCRIPT:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.formsubmit = function () {
}
$scope.states = {
"IN": [
"Delhi",
"Goa",
"Gujarat",
"Himachal Pradesh",
]
};
$scope.countries = {
IN: ["India"],
ZA: ["South Africa"],
AT: ["Austria"]
}
$scope.state1 = Object.keys($scope.countries)[0];
$scope.lastName = "Doe";
});
jsfiddle
<form role="form" name="signupForm" ng-submit="signup()" novalidate>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="clearfix"> </div>
<div class="inputGroup">
<input type="text" id="su_username" name="username" class="form-control input-md"
ng-model="user.username" ng-minlength="8" required>
<span class="inputBar"></span>
<label translate="signup.form.username">Username</label>
<span class="text-danger" ng-show="signupForm.username.$dirty && signupForm.username.$invalid">
<span ng-show="signupForm.username.$error.required" translate="signup.messages.validate.username.required">Username is required.</span>
<span ng-show="signupForm.username.$error.minlength" translate="signup.messages.validate.username.minlength">Username must be at least 8 characters.</span>
</span>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="clearfix"> </div>
<div class="inputGroup">
<input type="email" name="email" id="su_email" class="form-control input-md"
ng-model="user.email" required>
<span class="inputBar"></span>
<label translate="signup.form.email">Email Address</label>
<span class="text-danger" ng-show="signupForm.email.$dirty && signupForm.email.$invalid">
<span ng-show="signupForm.email.$error.required" translate="signup.messages.validate.email.required">Email is required.</span>
<span ng-show="signupForm.email.$error.email" translate="signup.messages.validate.email.invalid">Invalid email address.</span>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block"
ng-disabled="signupForm.$invalid ">
1st of all you need to give your form a name here its signupForm .
2nd from there you need to give your input fields names for example here they areusername and email.
Then you can use various angular validation directives to set validation constrains like require , length then you can check for validation error using signupForm.username.$invalid and check various error like signupForm.email.$error.email.
Finally if you want to check if the whole from is valid use signupForm.$invalid
and for number validation use
angular.module('test')
.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
val = '';
}
var clean = val.replace( /[^0-9\.]/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
you can find github example from here
var app = angular.module('jsbin', []);
app.controller('DemoCtrl', function() {
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Angular JS</title>
</head>
<body ng-app="jsbin">
<div ng-controller="DemoCtrl as demo">
<form name="form" novalidate ng-submit="validate()">
<input type="email" name="email" ng-model="email" required />
<span class="help-inline" ng-show="submitted && form.email.$error.required">Required</span>
<span class="help-inline" ng-show="submitted && form.email.$error.email">Invalid email</span>
<button type="submit" class="btn btn-primary btn-large" ng-disabled="submitted && form.email.$error.required || submitted && form.email.$error.email" ng-click="submitted=true">Submit</button>
</form>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
</body>
</html>
Check This Out.
In order to disable the submit button, you can do something like this:
<form name="myForm">
<input ...>
...
<button type="button" ng-disabled="myForm.$invalid" ng-click="formsubmit();">
Submit
</button>
</form>
Notice that I have put ng-disabled with a condition of myForm being invalid. So, instead of waiting for user to click the button, we are disabling the submit button upfront when form is invalid!
For Email validation, I would suggest you to go with <input type = "email"...> unless you have specific email validation requirements not handled by type = "email"
Here's the updated fiddle which disables the submit button until we put a valid email address.
Edit: Here's an example of how ng-pattern can be used to validate email for given rules (i.e. email must contain #, dot and after dot minimum 2 & maximum 4 alphabet characters)
<input type="text" ng-model="user.email" name="email" required
ng-pattern="/[a-zA-Z0-9_.]+\#[a-zA-Z0-9_]+\.[a-zA-Z]{2,4}$/"/>
Here's the updated fiddle
Also, regex101 for the email validation regex

JavaScript - Bootstrap Validator

I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)
I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

Form validation using AngularJS not working

I am planning to do a simple form validation using AngularJS but it seems not to be working. Here is my plunkr file: http://plnkr.co/edit/sEPAhszlFofLfb87uh8S.
I don't know why, everything seems good but it is not firing.
My html file:
<html>
<head>
<!-- CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
<style>
body { padding-top:30px; }
</style>
<!-- JS -->
<script src="http://code.angularjs.org/1.2.6/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<!-- PAGE HEADER -->
<div class="page-header">
<h1>AngularJS Form Validation</h1>
</div>
<!-- =================================================================== -->
<!-- FORM ============================================================== -->
<!-- =================================================================== -->
<!-- pass in the variable if our form is valid or invalid -->
<form name="regForm" ng-submit="submitForm(regForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group item item-input" ng-class="{ 'has-error' : regForm.name.$invalid && (regForm.name.$dirty || submitted)}">
<input type="text" name="name" class="form-control" ng-model="user.name" placeholder="Full Name" ng-required="true">
<br/>
<p ng-show="regForm.name.$error.required && (regForm.name.$dirty || submitted)" class="help-block">Please provide your full name</p>
</div>
<div class="form-group item item-input" ng-class="{ 'has-error' : regForm.email.$invalid && (regForm.email.$dirty || submitted)}">
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Email Address" ng-required="true">
<p ng-show="regForm.email.$error.required && (regForm.email.$dirty || submitted)" class="help-block">Email is required.</p>
<p ng-show="regForm.email.$error.email && (regForm.email.$dirty || submitted)" class="help-block">Enter a valid email.</p>
</div>
<div class="form-group item item-input" ng-class="{ 'has-error' : regForm.contactno.$invalid && (regForm.contactno.$dirty || submitted) }">
<input type="text" name="contactno" class="form-control" ng-model="user.contactno" placeholder="Phone number" ng-pattern="^0[0-9]{2}[- ]?[0-9]{3} ?[0-9]{4,5}$" maxlength="11" ng-required="true">
<p ng-show="regForm.contactno.$error.required && regForm.contactno.$error.pattern && (regForm.contactno.$dirty || submitted)" class="help-block">Enter a valid phone number.</p>
</div>
<div class="form-group item item-input" ng-class="{ 'has-error' : regForm.org.$invalid && (regForm.org.$dirty || submitted)}">
<input type="text" name="org" class="form-control" ng-model="user.org" placeholder="Organization Name" ng-required="true">
<p ng-show="regForm.org.$error.required && (regForm.org.$dirty || submitted)" class="help-block">Please input name of your organization</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
My js file:
var validationApp = angular.module('validationApp', []);
// create angular controller
validationApp.controller('mainController', function($scope) {
// function to submit the form after all validation has occurred
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
}
};
});
I just need it to validate that all required fields have the related input and not empty fields.
Your ng-pattern should be ng-pattern="/^[0-9]{2}[- ]?[0-9]{3} ?[0-9]{4,5}$/" instead of ng-pattern="^0[0-9]{2}[- ]?[0-9]{3} ?[0-9]{4,5}$" regx pattern should use escaping character / at the start & end of the expression.
Working Plunkr
Your pattern is wrong, from the angular documentation:
ngPattern (optional) string
Sets pattern validation error key if the
value does not match the RegExp pattern expression. Expected value is
/regexp/ for inline patterns or regexp for patterns defined as scope
expressions.
So putting a forward slash at the start and end of your pattern should work

angularjs form reset error

i'm trying to do a form with validations using angularjs and so far i did a good job. But when i commit my reset button all the fields reset except for the error messages i get from my validation part. How can i get rid of all the fields and error messages when i reset my form.
This is how it is when i press my reset button
this is my code
<div class="page-header"><center><h2>Give us your Feedback</h2></center></div>
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
<label>Name*</label>
<input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block">
<font color="#009ACD">You name is required.</font>
</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty }">
<label>Email</label>
<input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">
<font color="#009ACD">Enter a valid email.</font>
</p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
<label>Description</label>
<input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required>
<font color="white">
<p ng-show="userForm.username.$error.minlength" class="help-block">
<font color="#009ACD">Description is too short.</font>
</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">
<font color="#009ACD">Description is too long.</font>
</p>
</font>
</div>
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="reset()" padding-top="true"
>
Reset
</button>
<button class="button button-block button-positive" style="display: inline-block;width:100px "
ng-click="submit()"
padding-top="true"
>
Submit
</button>
</div>
</form>
</div>
My controller
.controller('ContactCtrl', function($scope,$state,$ionicPopup, $timeout) {
$scope.showfeedback = function() {
$state.go('app.sfeedback');
};
$scope.submitForm = function(isValid) {
$scope.submitted = true;
// check to make sure the form is completely valid
if (!isValid) {
var alertPopup = $ionicPopup.alert({
title: 'Invalid data entered!',
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Feedback submitted',
});
}
};
$scope.reset = function() {
var original = $scope.user;
$scope.user= angular.copy(original)
$scope.userForm.$setPristine()
};
})
var original = $scope.user;
when resetting :
$scope.user= angular.copy(original);
$scope.userForm.$setPristine();
remove
type='reset' in <button>
here is the Angular Documentation for form controllers.
Use the following to reset dirty state
$scope.form.$setPristine();
Use the following to reset to clear validation
$scope.form.$setValidity();
There's API documentation on the FormController.
This allowed me to find that there's other methods to call such as:
$setUntouched() - which is a function I was using if the user has focused on the field, and then left the field, this clears this feature when you run it.
I created a simple form reset function which you can use too.
// Set the following in your controller for the form/page.
// Allows you to set default form values on fields.
$scope.defaultFormData = { username : 'Bob'}
// Save a copy of the defaultFormData
$scope.resetCopy = angular.copy($scope.defaultFormData);
// Create a method to reset the form back to it's original state.
$scope.resetForm = function() {
// Set the field values back to the original default values
$scope.defaultFormData = angular.copy($scope.resetCopy);
$scope.myForm.$setPristine();
$scope.myForm.$setValidity();
$scope.myForm.$setUntouched();
// in my case I had to call $apply to refresh the page, you may also need this.
$scope.$apply();
}
In your form, this simple setup will allow you to reset the form
<form ng-submit="doSomethingOnSubmit()" name="myForm">
<input type="text" name="username" ng-model="username" ng-required />
<input type="password" name="password" ng-model="password" ng-required />
<button type="button" ng-click="resetForm()">Reset</button>
<button type="submit">Log In</button>
</form>
I went with...
$scope.form.$setPristine();
$scope.form.$error = {};
Feels hacky... but a lot about angular does.
Besides... this was the only thing that worked.
I had the same problem and used the following code to completely reset the form :
$scope.resetForm = function(){
// reset your model data
$scope.user = ...
// reset all errors
for (var att in $scope.userForm.$error) {
if ($scope.userForm.$error.hasOwnProperty(att)) {
$scope.userForm.$setValidity(att, true);
}
}
// reset validation's state
$scope.userForm.$setPristine(true);
};
To me using $setPristine to reset the form is a hack.
The real solution is to keep it like it should be:
<button type="reset" ng-click="reset()"></button>
then in angular:
var original = angular.copy($scope.user);
$scope.reset = function() {
$scope.user = angular.copy(original);
};
and that's it.
Use this
<button type="button" ng-click='resetForm()'>Reset</button>
In Controller
$scope.resetForm = function(){
$scope.userForm.$dirty = false;
$scope.userForm.$pristine = true;
$scope.userForm.$submitted = false;
};
Its working for me
In case you don't have a master (dynamic models from server), and you want to reset the form but only the binded part of the model you can use this snippet:
function resetForm(form){
_.forEach(form, function(elem){
if(elem !== undefined && elem.$modelValue !== undefined){
elem.$viewValue = null;
elem.$commitViewValue();
}
});
}
And then you can use it with a standard reset button like so:
<button type="reset" ng-click="resetForm(MyForm);MyForm.$setValidity();">reset</button>
Give us your Feedback
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
<label>Name*</label>
<input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block"><font color="#009ACD">You name is required.</font></p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty }">
<label>Email</label>
<input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block"><font color="#009ACD">Enter a valid email.</font></p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
<label>Description</label>
<input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required>
<font color="white"><p ng-show="userForm.username.$error.minlength" class="help-block"><font color="#009ACD">Description is too short.</font></p>
<p ng-show="userForm.username.$error.maxlength" class="help-block"><font color="#009ACD">Description is too long.</font></p>
</div>
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="reset()"padding-top="true">Reset</button>
<button class="button button-block button-positive" style="display: inline-block; width:100px" ng-click="submit()"padding-top="true">Submit</button>
</div>
</form>
I kept the type="reset" in my button. What I did was the ng-click="resetForm(userForm)" (using userFrom to match your example) and the controller defines resetForm() as
scope.resetForm = function(controller) {
controller.$commitViewValue();
controller.$setPristine();
};
Here is what happens:
When the reset button is clicked, it will bring back the original values as specified by the value attribute on the input
The $commitViewValue() will force the write of whatever is on the view presently to the $modelValue of each field (no need to iterate manually), without this the last $modelValue would still be stored rather than reset.
The $setPristine() will reset any other validation and submitted fields.
In my angular-bootstrap-validator I already had the FormController as such I didn't need to pass in the form itself.
In My Form
<form angular-validator-submit="submitReview()" name="formReview" novalidate angular-validator>
<input type="text" name="Rating" validate-on="Rating" class="form-control"
ng-model="Review.Rating" required-message="'Enter Rating'" required>
<button type="button" ng-click="reset()">Cancel</button>
</form>
app.controller('AddReview', function ($scope) {
$scope.reset= function () {
$scope.formReview.reset()
};
});
only need to call $scope.formReview.reset() where formReview is my form name.
My form is inside another scope so my solution need to use $$postDigest
$scope.$$postDigest(function() {
$scope.form.$error = {};
});
To reset the validations we have to do two things:
clear the fields
Add the following:
$scope.programCreateFrm.$dirty = false;
$scope.programCreateFrm.$pristine = true;
$scope.programCreateFrm.$submitted = false;
programCreateFrm is the name of the form.
For example:
<form name="programCreateFrm" ng-submit="programCreateFrm.$valid && createProgram(programs)" novalidate>
This code is working for me.

Categories

Resources