Form validation using AngularJS not working - javascript

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

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

Validating all form fields -- function not working correctly

I created a html form and a function validateForm() to validate the form fields. However the function is only reporting issues with wrong email input, and its not validating the other fields in the form. Can you check my code to see if i have any errors.
Thanks
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Support Center</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/layout.css" type="text/css">
<link rel="stylesheet" href="styles/Form.css" type="text/css">
<script type="text/javascript" src="Form.js"></script>
</head>
<body>
<div class="wrapper row1">
<header id="header" class="clear">
<div id="hgroup">
<h1>Support Center</h1>
<h2>Welcome to our website</h2>
</div>
<nav>
<ul>
<li>Home</li>
<li>Our Staff</li>
<li>Location</li>
<li>Help</li>
<li class="last"></li>
</ul>
</nav>
</header>
</div>
</body>
<!-- content -->
<body>
<h1>Help is here!</h1>
<form>
<h1>Should you need assistance, please do not hesitate to contact us:</h1>
<div class="contentform">
<div id="sendmessage"> Your form has been sent successfully. Thank you. </div>
<div class="leftcontact">
<div class="form-group">
<p>Surname<span>*</span></p>
<span class="icon-case"><i class="fa fa-male"></i></span>
<input type="text" name="lastName" id="lastName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>First Name <span>*</span></p>
<span class="icon-case"><i class="fa fa-user"></i></span>
<input type="text" name="firstName" id="firstName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>E-mail <span>*</span></p>
<span class="icon-case"><i class="fa fa-envelope-o"></i></span>
<input type="email" name="emailAddress" id="emailAddress"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Office <span>*</span></p>
<span class="icon-case"><i class="fa fa-location-arrow"></i></span>
<input type="text" name="office" id="office"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Desk <span>*</span></p>
<span class="icon-case"><i class="fa fa-map-marker"></i></span>
<input type="text" name="deskNumber" id="deskNumber"/>
<div class="validation"></div>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<p>Phone number <span>*</span></p>
<span class="icon-case"><i class="fa fa-phone"></i></span>
<input type="text" name="mobilePhone" id="mobilePhone"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Job Number <span>*</span></p>
<span class="icon-case"><i class="fa fa-building-o"></i></span>
<input type="text" name="jobNumber" id="jobNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Computer <span>*</span></p>
<span class="icon-case"><i class="fa fa-info"></i></span>
<input type="text" name="computerNumber" id="computerNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comment-o"></i></span>
<select name="Problem">
<option value="New User">New User</option>
<option value="Delete User">Delete User</option>
<option value="Lost File">Lost File</option>
<option value="New Software Installation">New Software Installation</option>
<option value="Virus Checking">Virus Checking</option>
</select>
<div class="validation"></div>
</div>
<div class="form-group">
<p>A little about your problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comments-o"></i></span>
<textarea name="message" rows="14"></textarea>
<div class="validation"></div>
</div>
</div>
</div>
<button type="submit" class="bouton-contact">Send</button>
</form>
</body>
</html>
</body>
</html>
Code
function validateForm() {
var letters = "[A-Za-z]+$";
var numbers = "^[0-9]+$";
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jobNumber = document.getElementById("jobNumber").value;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var mobilePhone = document.getElementById("mobilePhone").value;
var emailAddress = document.getElementById("emailAddress").value;
var officeNumber = document.getElementById("office").value;
var deskNumber = document.getElementById("deskNumber").value;
var computerNumber = document.getElementById("computerNumber").value;
if(jobNumber != "" && firstName != "" && lastName != "" && mobilePhone != "" && emailAddress != "" && officeNumber != "" && deskNumber != "" && computerNumber != "") {
if(jobNumber.length == 5 && jobNumber.match(numbers)) {
if(firstName.match(letters) && lastName.match(letters)) {
if(mobilePhone.length == 10 && mobilePhone.match(numbers)) {
if(emailAddress.match(emailReg)) {
alert("Form submitted!");
return true;
}
else {
alert("Please enter a valid email");
return false;
}
}
else {
alert("Please enter a valid mobile number");
return false;
}
}
else {
alert("Please enter a valid first name and last name");
return false;
}
}
else {
alert("Please enter a valid job number");
return false;
}
}
else {
alert("Please enter in all fields");
return false;
}
}
Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several.
Also, the reason the email is the only one working is because the browser is validating the email without using your JS.
First I would ditch all the variables declared and replace it with the form object.
var formObject = document.getElementById('contentform');
Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.
var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
errorList.push('Please enter a valid job number');
isValid = false;
}
Then rinse and repeat for each element required. After that, just return the list and status (isValid).
// this should be on its own at the bottom of your function right before you return
if (!isValid) {
alert(errorList);
// I would add some formatting or preferably display in the form view.
}
return isValid;
html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>
Also, these
if (!isValid) {
alert(errorList);
}
should be removed from each if statement and placed at the bottom after all have been checked.
Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.
//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />
//javascript
function validation()
{
var email = document.getElementById('email').value;
if(email == '' || !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
{
document.getElementById('emailerror').style.display = 'inline';
var error=1;
}
else
{
document.getElementById('emailerror').style.display = 'none';
}
if(error == 1)
{
return false;
}
else
{
return true;
}
}
now your email validation works fine, thanks

How do I prevent form submission in Angularjs if I am submitting the form using enter key?

I have applied validation to my form (It has only two fields) but don't know how to prevent it from submitting,Current flow is: After pressing enter key the student's name and marks are added on localstorage and are displayed on the screen from there but I am unable to prevent empty data from submitting.
These are my js functions:
$scope.searchEnter = function() {
if (event.which == 13 && $scope.student != "") {
$scope.addStudent();
}
};
$scope.addStudent = function() {
if ($scope.marks > 65) {
var pass = true;
} else {
pass = false;
}
$scope.students.push({ 'studentName': $scope.student, 'Marks': parseInt($scope.marks), 'pass': pass });
$scope.student = '';
$scope.marks = '';
localStorage['studentsList'] = JSON.stringify($scope.students);
};
This is the html part:
<div class="row">
<div class="col-xs-12">
<form class="form-horizontal" novalidate name="studentForm" >
<div class="form-group">
<label class="col-sm-2 control-label" for="student_name">Student's Name</label>
<div class="col-sm-5">
<input ng-model="student" ng-keyup="searchEnter()" type="text" class="form-control" id="student_name" ng-required="true" name="stdname">
<div ng-show="studentForm.stdname.$touched && studentForm.stdname.$invalid">
<small style="color:red; display:block;">Enter a valid name </small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="student_marks">Marks obtained</label>
<div class="col-sm-5">
<input ng-model="marks" ng-keyup="searchEnter()" type="number" class="form-control" id="student_marks" ng-required="true">Press ENTER to insert student's data in the table.</div>
</div>
</form>
</div>
</div>
Supposing that your fields are correctly validating, to prevent the submit you could use ngDisabled directive, as below:
<button type="submit" ng-disabled="form.$invalid">Submit</button>
EDIT: Since the OP provided the full code I was able to give the correct answer, that is:
Change the check to:
if (event.which == 13 && $scope.student && $scope.marks) {
Snippet working based on your code:
(function() {
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.students = [];
$scope.searchEnter = function() {
if (event.which == 13 && $scope.student && $scope.marks) {
$scope.addStudent();
}
};
$scope.addStudent = function() {
console.log('addStudent called');
$scope.students.push({
'studentName': $scope.student,
'Marks': $scope.marks,
'pass': $scope.marks > 65
});
$scope.student = '';
$scope.marks = '';
localStorage['studentsList'] = JSON.stringify($scope.students);
};
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-controller="MainCtrl">
<div class="row">
<div class="col-xs-12">
<form class="form-horizontal" novalidate name="studentForm">
<div class="form-group">
<label class="col-sm-2 control-label" for="student_name">Student's Name</label>
<div class="col-sm-5">
<input ng-model="student" ng-keyup="searchEnter()" type="text" class="form-control" id="student_name" ng-required="true" name="stdname">
<div ng-show="studentForm.stdname.$touched && studentForm.stdname.$invalid">
<small style="color:red; display:block;">Enter a valid name </small>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="student_marks">Marks obtained</label>
<div class="col-sm-5">
<input ng-model="marks" ng-keyup="searchEnter()" type="number" class="form-control" id="student_marks" ng-required="true">Press ENTER to insert student's data in the table.</div>
</div>
</form>
</div>
</div>
</body>
</html>
Tips:
The ngModel $scope.marks is already a number, you don't need to to do any parse, so you can have 'Marks': $scope.marks.
The check of pass can simply reduced to: 'pass': $scope.marks > 65

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