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

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

Related

AngularJS - submit form programmatically after validation

I have recently started working on AngularJS 1.6.
I am trying to submit a form programmatically. The reason is I want to validate a few fields (required field validation). I have spent a lot of efforts (probably 3-4 hours) trying to make this work but none of the existing answers on stack overflow or AngularJS docs seems to be working for me today (strange), hence I am posting this as last resort.
Below is my html
<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
<div>
{{message}}
</div>
<div>
<label>User Name</label>
<input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" />
</div>
<div>
<label>Password</label>
<input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" />
</div>
<div>
<input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" />
</div>
</form>
My angular code
var demoApp = angular.module('demoApp', []);
demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {
$scope.loginUser = function () {
var form = document.getElementById("loginform");
//var form = $scope.loginform; - tried this here...
//var form = $scope["#loginform"]; tried this
//var form = angular.element(event.target); - tried this...
// tried a lot of other combinations as well...
form.attr("method", "post");
form.attr("action", "Home/Index");
form.append("UserName", $scope.user.UserName);
form.append("Password", $scope.user.Password);
form.append("RememberMe", false);
form.submit();
};
}]);
I keep on getting error 'attr' is not a function.
All I need is submit a form using post method, with values. Just before that I am trying to intercept the submit call and check for validations.
I am open to try any other approach as well. Such as changing the input type from submit to button. Putting the input outside the form. I would be more than happy if validations and submit both can happen any which way. I just want it to post back the values after validating on the client side and then the server will take care of the redirect.
Note: I want the form to do a full postback so that I can get it to redirect to another form. (I know I could use Ajax, but some other day, may be!)
1st of all avoid doing var form = document.getElementById("loginform");. Instead of using form.submit you can use the following code. Do it the angular way cheers :D
$scope.loginUser = function () {
if($scope.loginform.$valid){
user.rememberme=false;
$http({
url: 'Home/Index',
method: "POST",
data: user
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
}
};
this is a code to validation if validation not complate button is not enable
<form method="post" id="loginform" name="loginform" ng-submit="loginUser()" novalidate>
<div>
{{message}}
</div>
<div>
<label>User Name</label>
<input type="text" id="txtUserName" required ng-model="user.UserName" name="UserName" />
</div>
<div>
<label>Password</label>
<input type="text" id="txtPassword" ng-model="Password" name="user.Password"required />
</div>
<div>
<input type="submit" ng-disabled="myForm.UserName.$invalid || myForm.Password.$invalid" id="btnLogin" title="Save" name="btnLogin" value="Login" />
</div>
</form>
You should use $scope when trying to access the form, something like $scope.loginform. But......
Take a look at ng-messages. Heres an example using ng-messages with your form:
<form id="loginform" name="loginform" ng-submit="loginUser()">
<div>
{{message}}
</div>
<div>
<label>User Name</label>
<input type="text" id="txtUserName" ng-model="user.UserName" name="user.UserName" required/>
<div class="help-block" ng-messages="loginform.txtUserName.$error" ng-show="loginform.txtUserName.$touched">
<p ng-message="required">Username is required.</p>
</div>
</div>
<div>
<label>Password</label>
<input type="text" id="txtPassword" ng-model="user.Password" name="user.Password" required/>
<div class="help-block" ng-messages="loginform.txtPassword.$error" ng-show="loginform.txtPassword.$touched">
<p ng-message="required">Password is required.</p>
</div>
</div>
<div>
<input type="submit" id="btnLogin" title="Save" name="btnLogin" value="Login" ng-click="loginUser()" />
</div>
</form>
Add ngMessages:
var demoApp = angular.module('demoApp', ['ngMessages']);
demoApp.controller("homeController", ["$scope", "$timeout", function ($scope, $timeout) {
$scope.loginUser = function () {
if($scope.loginform.$valid){
//Code to run before submitting (but not validation checks)
} else{
return false;
}
};
}]);
Don't forget to include ngMessages in your app declaration and include the ngMessages.js script file. Note how you can simply use HTML5 validators.
I found the thing I was looking for. In the end I had to create a directive for validating and then submitting. So I am posting it here as a whole answer.
My HTML
<div ng-controller="homeController" ng-init="construct()">
<form method="post" action="Index" role="form" id="loginform" name="loginform" ng-form-commit novalidate class="ng-pristine ng-invalid ng-invalid-required">
<div class="form-group">
<label for="UserName">User ID</label>
<input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
id="UserName" name="UserName" ng-model="user.UserName" type="text" value=""
ng-change="userNameValidation = user.UserName.length == 0">
<span class="field-validation-error text-danger" ng-show="userNameValidation">The User ID field is required.</span>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input autocomplete="off" class="form-control ng-valid ng-touched ng-pristine ng-untouched ng-not-empty"
id="Password" name="Password" ng-model="user.Password" type="password" value=""
ng-change="passwordValidation = user.Password.length == 0">
<span class="field-validation-error text-danger" ng-show="passwordValidation">The Password field is required.</span>
</div>
<div>
<input type="button" id="btnLogin" title="Login" name="btnLogin" value="Login" ng-click="validateUser(loginform)" />
</div>
</form>
</div>
Look for ng-form-commit on the form element. It is the directive that I created.
My Angular code
var demoApp = angular.module('demoApp', []);
demoApp.factory("commonService", function () {
return {
isNullOrEmptyOrUndefined: function (value) {
return !value;
}
};
});
//This is the directive that helps posting the form back...
demoApp.directive("ngFormCommit", [function () {
return {
require: "form",
link: function ($scope, $el, $attr, $form) {
$form.commit = function () {
$el[0].submit();
};
}
};
}]);
demoApp.controller("homeController", ["$scope", "commonService", function ($scope, commonService) {
$scope.construct = function construct() {
$scope.user = { UserName: "", Password: "" };
};
$scope.userNameValidation = false;
$scope.passwordValidation = false;
$scope.isFormValid = false;
$scope.validateUser = function ($form) {
$scope.isFormValid = true;
$scope.userNameValidation = commonService.isNullOrEmptyOrUndefined($scope.user.UserName);
$scope.passwordValidation = commonService.isNullOrEmptyOrUndefined($scope.user.Password);
$scope.isFormValid = !($scope.userNameValidation || $scope.passwordValidation);
if ($scope.isFormValid === true) {
$scope.loginUser($form);
}
};
$scope.loginUser = function ($form) {
$form.commit();
};
}]);
I found the directive here
Example using Angular 1.5 components.
(function(angular) {
'use strict';
function DemoFormCtrl($timeout, $sce) {
var ctrl = this;
this.$onInit = function() {
this.url = $sce.trustAsResourceUrl(this.url);
/*$timeout(function() {
ctrl.form.$$element[0].submit();
});*/
};
this.validate = function(ev) {
console.log('Running validation.');
if (!this.form) {
return false;
}
};
}
angular.module('app', [])
.component('demoForm', {
template: `
<p>To run this demo allow pop-ups from https://plnkr.co</p>
<hr>
<p>AngularJS - submit form programmatically after validation</p>
<form name="$ctrl.form" method="get" target="blank" action="{{::$ctrl.url}}" novalidate
ng-submit="$ctrl.validate($event)">
<input type='hidden' name='q' ng-value='::$ctrl.value'>
<input type='hidden' name='oq' ng-value='::$ctrl.value'>
<input type="submit" value="submit...">
</form>`,
controller: DemoFormCtrl,
bindings: {
url: '<',
value: '<'
}
});
})(window.angular);
https://plnkr.co/edit/rrruj6vlWrxpN3od9YAj?p=preview

Enable next form element with the value of previous

I do need to create a form. In that form I need to enable form element one by one. That mean, If an user entered valid data to first element then I want to autofocus next element and so on.
NOTE: When page is load I want to keep all the elements disable except first element.
This is HTML of my form.
<form role="form" class="banner" method="post" action="">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="name" placeholder="Your Name" class="form-control first-name sequence" autocomplete="off" required>
<label for="name" class="glyphicon glyphicon-user" data-toggle="tooltip" data-placement="left" title="Enter Your Name"></label>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="email" name="email" placeholder="Your Email" class="form-control email_address sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-envelope" rel="tooltip" title="Enter Your Email"></label>
<span class="email-error"></span>
</div>
</div>
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="phone" placeholder="Your Phone Number Eg: xx-xxx-xxx" class="form-control phone-number sequence" autocomplete="off" disabled required>
<label for="email" class="glyphicon glyphicon-phone" rel="tooltip" title="Enter Your Phone Number"></label>
</div>
</div>
<div class="element-left">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-date" placeholder="Pick Up Date" class="form-control datepicker sequence" autocomplete="off">
<label for="date" class="glyphicon glyphicon-calendar" rel="tooltip" title="Prefered Charter Date"></label>
</div>
</div>
</div>
<div class="element-right">
<div class="form-group">
<div class="icon-addon addon-md">
<input type="text" name="charter-time" placeholder="Pick Up Time" class="form-control timepicker sequence" autocomplete="off">
<label for="time" class="glyphicon glyphicon-time" rel="tooltip" title="Time of Charter"></label>
</div>
</div>
</div>
<p class="form-actions">
<button type="submit" name="submit" class="btn btn-default btn-block">
<span class="btn-orange-inner">Send</span>
</button>
</p>
</form>
This is how I tried it in jQuery:
// form validation
function fakeValidator(event) {
var flag = false;
var $element = $(event.target);
var values = $element.val();
if (values.length >= 3) {
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
flag =true;
} else {
flag =false;
}
if(flag){
//alert('hi');
$element.addClass('valid');
enableNextElement(event);
} else{
alert('hi el');
$element.removeClass('valid');
//$element.addAttr('disabled');
}
}
function validemail(value){
var emailReg ="/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/";
}
function enableNextElement(event) {
var $element = $(event.target);
if ($element.hasClass('valid')) {
$element.closest('.form-group')
.next('.form-group')
.find('.sequence')
.removeAttr('disabled');
}
}
$('.sequence').on('blur keyup', fakeValidator);
But my problem is, if I entered an invalid email next element is enabling. But I want to enable next element if its a valid email in email field.
Can anybody tell me what is wrong with this?
Thank you.
2 things:
You should return true or false from your email validation function i.e. validemail
Your regex is stored as string, and hence you cannot apply test function on it. Remove wrapping it in " "
Above mentioned changes will give you desired result.
function validemail(value){
var emailReg =/^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; //regex
return emailReg.test(value); //use test which returns true or false
}
UPDATE
DEMO
It will still enable the phonenumber because you have validation written in such a way.
Your Validation:
if (values.length >= 3) {
//this is ok for name
if($element.hasClass('email_address')) {
if(validemail(values)){
flag = true;
}else{
flag =false;//even though flag is false here
}
}
flag =true; //when it comes to this line it again makes it to true
//and for email along with length>3, valid email address has also to be validated
} else {
flag =false;
}
My workaround
if (values.length >= 3) {
flag =true; //set this first
if($element.hasClass('email_address')) {//then perform other validations
if(validemail(values)){
flag = true ;
}else{
flag =false;
}
}
} else {
flag =false;
}

jQuery Validate forms by sections

i am trying to use jQuery validate to validate a big form that i have cut in 3 different sections.
personal information
job information
additional information
is there a way for me to validate the content every time the user hits continue? and then when they get to the last section they can submit the ENTIRE form?
form
<form method="post" name="form" id="form" class="form">
<div class="section_one form-wrapper-top-margin active">
<div class="columns-2 float-left">
<input name="name" id="name" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="email" id="email" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_1"/>
</div>
</div>
<div class="section_two form-wrapper-top-margin">
<div class="columns-1 margin-0">
<input name="address" id="address" type="text" class="" value=""/>
</div>
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_2"/>
</div>
</div>
<div class="section_there form-wrapper-top-margin">
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="submit" type="submit" id="submitbtn" value="Send your message"/>
</div>
</div>
</div>
</div>
</form>
i dont put the jQuery code here because i dont know where to start. i know jQuery validate, validates an entire form, but i never seen it done by sections with out splitting it into 3 different forms.
Thanks for the help...
You can do like this also:-
$(".section_two").click(function(){
//Your code for validation of section one.
});
$(".section_three").click(function(){
//Your code for validation of section one and section two.
});
$("#submitbtn").click(function(){
//Your code for validation of section three.
});
Let me know if this helps.
I found the answer here:
jQuery button validate part of a form at a time
this is the code i used
var validator = $('#form').validate({
ignore: 'input.continue,input#submitbtn',
rules: {
name: {
required: true
},
email: {
required : true
},
date: {
required: true
},
},
messages: {
name: "Enter your name",
email: {
require: "Please enter a valid email address",
email: "Enter a valid email"
},
},
errorPlacement: function(error, element) { },
});
$('#continue1').on('click', function(){
var tab = $(".section_one.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-1080px'});
}
});
$('#continue2').on('click', function(){
var tab = $(".section_two.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-2160px'});
}
});
thanks for everyone's advise...

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.

AngularJs radio button dirty validation not working

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.

Categories

Resources