angular js form showing validation alerts all the time - angularjs

I am really new to angular and I am just browsing its capabilities which are incredibly impressive so far...I created this simple username field validation:
<!Doctype html>
<html>
<head>
<title>form validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
</head>
<body>
<form name="form">
Name:
<input type="text"
name="uName"
placeholder="username"
ng-minlength=3
ng-maxlength=20
ensure-unique="username" required /><br />
<div ng-show="form.uName.$dirty && form.uName.$invalid">
<small ng-show="form.uName.$error.required">please put your username in</small>
<small ng-show="form.uName.$error.minlength">it has to be at least 3 characters</small>
<small ng-show="form.uName.$error.maxlength">it can't be longer than 20 characters</small>>
<small ng-show="form.uName.$error.unique">this one has already been taken</small>
</div>
</form>
</body>
</html>
however it just shows all of the validation errors...I am now sure why, I am also missing a model, but I again I don't know if it is necessary.

http://jsbin.com/hekaz/1/edit
<form name="form">
Name:
<input type="text"
name="uName"
placeholder="username"
ng-minlength=3
ng-maxlength=20
ensure-unique="username" required ng-model="username"/><br />
<div ng-show="form.uName.$dirty && form.uName.$invalid">
<small ng-show="form.uName.$error.required">please put your username in</small>
<small ng-show="form.uName.$error.minlength">it has to be at least 3 characters </small>
<small ng-show="form.uName.$error.maxlength">it can't be longer than 20 characters</small>
<small ng-show="form.uName.$error.unique">this one has already been taken</small>
</div>
</form>

I noticed three things.
1.You miss ng-app on the html tag:
<html ng-app="myApp">
2.You miss a controller, ie:
<script>
var myApp = angular.module('myApp', []);
function ControllerCtrl ($scope) {
$scope.username='';
};
</script>
3.You miss ng-model in your input:
ng-model="username"
Full working code:
<!Doctype html>
<html ng-app="myApp">
<head>
<title>form validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
function ControllerCtrl ($scope) {
$scope.username='';
};
</script>
</head>
<body>
<form name="form">
Name:
<input type="text"
name="uName"
placeholder="username"
ng-minlength=3
ng-maxlength=20
ensure-unique="username" required ng-model="username"/><br />
<div ng-show="form.uName.$dirty && form.uName.$invalid">
<small ng-show="form.uName.$error.required">please put your username in</small>
<small ng-show="form.uName.$error.minlength">it has to be at least 3 characters</small>
<small ng-show="form.uName.$error.maxlength">it can't be longer than 20 characters</small>>
<small ng-show="form.uName.$error.unique">this one has already been taken</small>
</div>
</form>
</body>
</html>

Related

Angularjs 1 form validation issue

I am using Angularjs 1 in my project.i am validating the form inside angular,so i am using form.$valid to check the form submitted is valid or not,but it is not working properly,not sure what i am missing
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title> Learning AngularJS Filters </title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script>
"use strict";
angular.module("myApp",[]);
angular.module("myApp").controller("SampleController",[function(){
this.user = {}
this.submitForm = function(form){
if(form.$valid){
window.alert("Valid")
}else{
window.alert("In Valid");
}
}
}]);
</script>
</head>
<body>
<div ng-controller="SampleController as sm" class="container">
<form name="sampleForm" novalidate>
<div class="form-group">
<label for="exampleInputEmail1"> Username </label>
<input type="text" class="form-control" ng-model="sm.user.name" id="exampleInputEmail1" placeholder="Enter Username" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" ng-model="sm.user.pwd" id="exampleInputPassword1" placeholder="Password" required>
</div>
<button type="submit" ng-click="sm.submitForm('sampleForm')" class="btn btn-primary">Submit</button>
<p> {{ sm.user }} </p>
</form>
</div> <!--/ container -->
</body>
</html>
I am always getting the alert message from the else part which states form invalid
Form directive is bounded to scope, so you need to write it as $scope.sampleForm.$valid. Since your name is dynamic, you can use a bracket notation: $scope[form].$valid. But either way you need to inject $scope into your controller.
Here is a demo:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title> Learning AngularJS Filters </title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script>
"use strict";
angular.module("myApp", []);
angular.module("myApp").controller("SampleController", ['$scope', function($scope) {
this.user = {}
this.submitForm = function(form) {
if ($scope[form].$valid) {
window.alert("Valid")
} else {
window.alert("In Valid");
}
}
}]);
</script>
</head>
<body>
<div ng-controller="SampleController as sm" class="container">
<form name="sampleForm" novalidate>
<div class="form-group">
<label for="exampleInputEmail1"> Username </label>
<input type="text" class="form-control" ng-model="sm.user.name" id="exampleInputEmail1" placeholder="Enter Username" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" ng-model="sm.user.pwd" id="exampleInputPassword1" placeholder="Password" required>
</div>
<button type="submit" ng-click="sm.submitForm('sampleForm')" class="btn btn-primary">Submit</button>
<p> {{ sm.user }} </p>
</form>
</div>
<!--/ container -->
</body>
</html>
You are passing form as a string in ng-click method not a form Object.So u have to pass the form object without Single-cotts.
ng-click="sm.submitForm('sampleForm')" to ng-click="sm.submitForm(sampleForm)"

ng-if does not work

In my project I am facing an issue that ng-if is not working. I want to remove/add text field when value of $scope.edit changes.
I have created a simplest of example in the jsfiddle below.
HTML
<div ng-app>
<div ng-controller="TodoCtrl">
<input type="checkbox" ng-model="edit" ng-init="edit = true">
<div ng-bind="edit"></div>
<div ng-if="edit">
<input type="text" ng-model="name" size="30" placeholder="New Name" />
</div>
</div>
</div>
JS
function TodoCtrl($scope) {
$scope.name = "Johny";
}
http://jsfiddle.net/U3pVM/32009/
Your Fiddle may not work because you are using Angular 1.0.1 which has some issue in ng-if.
Solution 1
If you are really using this version, you can replace ng-if by ng-show (which will create hidden elements in the DOM).
<div ng-show="edit">
Demo on JSFiddle using ng-show
Solution 2
Anyway, the best solution would be to use Angular 1.2+ which fixes ng-if bugs in ng-repeat. As you can see in the following snippet, I didn't change your code, and it works.
Demo on JSFiddle using ng-if
Some observations :
Seems that your angular version is old. hence, ng-if is not working.
If you want to use only existing angular version then you can use ng-show instead of ng-if.
Demo with ng-if :
function TodoCtrl($scope) {
$scope.name = "Johny";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
<input type="checkbox" ng-model="edit" ng-init="edit = true">
<div ng-bind="edit"></div>
<div ng-if="edit">
<input type="text" ng-model="name" size="30" placeholder="New Name" />
</div>
</div>
</div>
Demo with ng-show :
function TodoCtrl($scope) {
$scope.name = "Johny";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
<input type="checkbox" ng-model="edit" ng-init="edit = true">
<div ng-bind="edit"></div>
<div ng-show="edit">
<input type="text" ng-model="name" size="30" placeholder="New Name" />
</div>
</div>
</div>
Use ng-show instead
<div ng-show=edit>
<input type="text" ng-model="name" size="30" placeholder="New Name" />
</div>
DEMO
Update the angular version with 1.2 or above with ng-if
angular.module('myApp', [])
.controller('TestCtrl', function($scope) {
$scope.name = "Johny";
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS </title>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="TestCtrl">
<input type="checkbox" ng-model="edit" ng-init="edit = true">
<div ng-bind="edit"></div>
<div ng-show=edit>
<input type="text" ng-model="name" size="30" placeholder="New Name" />
</div>
</body>
</html>

fetch form values in AngularJs

I am new to AngularJS. I am creating single page application in which a form consists of multiple steps. I have used buttons and input fields. Form is getting submitted. I want to fetch the form fields values but i don't know the ways to do it. I have added my code. I want to see what user is filling so i can store the values in database. How do i get my values in console log.? Please someone guide me how to do it.
// Code goes here
var app = angular.module("MyApp", ["ngAnimate"]);
app.controller('MyCtrl', function($scope, $timeout) {
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('our form is amazing');
console.log(myform);
}
};
$scope.sliderValue = null;
$scope.name = '';
$scope.data = {
singleSelect: null,
multipleSelect: [],
option1: 'option-1',
};
$scope.forceUnknownOption = function() {
$scope.data.singleSelect = 'nonsense';
};
});
.circle
{
width:125px;
height:125px;
border:2px solid #FFF;
border-radius:62.5px;
font-size:18px;
color:#fff;
line-height:125px;
text-align:center;
background:#67508F
}
<!DOCTYPE html>
<html ng-app="MyApp" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300,500,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body ng-controller="MyCtrl">
<form name='myform' id="myform" ng-init="step = 1" ng-submit="submitForm(myform.$valid)">
<div ng-show="step==1">
<h3>Which step</h3>
<div ng-form='step1form'>
<button type="submit" class="OptionButton zoomIn" ng-disabled="!step1form.$valid" ng-click="step = 4">Go to step 4</button>
<button type="submit" class="OptionButton zoomIn" ng-disabled="!step1form.$valid" ng-click="step = 2">Go to step 2</button>
</div>
</div>
<div ng-show="step==2">
<h3 class="zoomIn">which step</h3>
<div ng-form='step2form'>
<div class="circle zoomIn" ng-disabled="!step2form.$valid" ng-click="step = 4"><span>Go to step 3</span></div>
</div>
</div>
<div ng-show="step==4">
<h3 class="zoomIn">Personal Details</h3>
<div ng-form='step14form'>
<input ng-model="FirstName" name="FirstName" type="text" ng-pattern="/^[a-zA-Z]*$/" class="zoomIn" placeholder="First Name" required>
<p class="ErrorMessage" ng-show="step4form.FirstName.$error.pattern">Please enter a valid First name.</p>
<input ng-model="LastName" name="LastName" type="text" ng-pattern="/^[a-zA-Z]*$/" class="zoomIn" placeholder="Last Name" required>
<p class="ErrorMessage" ng-show="step4form.LastName.$error.pattern">Please enter a valid Last name.</p>
<input ng-model="Phone" name="Phone" type="text" ng-pattern ="/^[789]\d{9}$/" class="zoomIn" placeholder="Phone" required>
<p class="ErrorMessage" ng-show="step4form.Phone.$error.pattern">Please enter a valid phone number.</p>
<input ng-model="Email" name="Email" type="text" ng-pattern ="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" class="zoomIn" placeholder="Email" required>
<p class="ErrorMessage" ng-show="step4form.Email.$error.pattern">Please enter a valid email address.</p>
</div>
<button type="submit" id="submit" class="Submit" ng-disabled="!myform.$valid" ng-click="submit()">Submit</button>
</div>
</form>
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-animate.js"></script>
<script src="script.js"></script>
</body>
</html>
My suggestion is to use data object for all of your ng-model inputs.
this is my JSFiddle example: JSFiddle
HTML:
<div ng-app>
<form ng-controller="FormController" name="myForm">
<div class="header padding-b--10">Form Area</div>
<div class="padding-b--10">
<input name="empId" placeholder="Employee ID" ng-model="data.empId"
style="padding:5px" required/>
<span ng-if="myForm.empId.$dirty && myForm.empId.$invalid" ng-bind="invalid" class="error"></span>
</div>
<div class="padding-b--10">
<input name="empEmail" type="email" placeholder="Email" ng-model="data.empEmail"
style="padding:5px" required/>
<span ng-if="myForm.empEmail.$dirty && myForm.empEmail.$invalid" ng-bind="invalid" class="error"></span>
</div>
<input type="button" value="Submit" ng-click="submit()" class="button" ng-disabled="myForm.$invalid">
<pre>{{data}}</pre>
<pre>myForm.empId.$valid = {{myForm.empId.$valid}}</pre>
<pre>myForm.empEmail.$valid = {{myForm.empEmail.$valid}}</pre>
</form>
</div>
JS:
function FormController($scope){
$scope.invalid = "Invalid";
$scope.submit = function(){
console.log($scope.data);
}
};

How to get dynamic value in angularjs

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Form Validation Example</h2>
<form name="myForm" novalidate="novalidate" data-ng-app="myapp" data-ng-controller="myc">
<p>User Name:<br>
<input type="text" name="fname" ng-model="fname" data-ng-minlength="10" data-ng-required="true" placeholder="Enter name" class="myname">
</p>
<p>Email:<br>
<input type="text" name="mail" ng-click="click($event)" data-ng-model="mail" data-ng-required="true" class="mymail" placeholder="enter mail id"/>
</p>
<input type="submit" value="click" ng-click="click()" />
</form>
<script src="angularjs/angular.js"></script>
<script>
var app =angular.module("myapp",[]);
app.controller('myc',function($scope)
{
var fname=$scope.fname;
$scope.click = function()
{
console.log("name "+fname);
alert("name "+fname);
}
});
</script>
</body>
</html>
I want to get a value which is entered by the user and after that I want to display it in the browser.
I don't want to set the value using $scope inside the controller.
I tried many times but I was unsuccessful to do it.
Can anybody help me?
Just pass the ng-model in click handler function as a parameter.
<input type="text" name="mail" data-ng-model="mail" data-ng-required="true" class="mymail" placeholder="enter mail id"/>
<input type="submit" value="click" ng-click="click(mail)" />
Show the model value in alert as
$scope.click = function(mail)
{
console.log("mail "+mail);
alert("mail "+mail);
}

AngularJS <input> validation with no enclosing <form>

Is it possible in Angular to validate a single, isolated <input> in a similar way the forms are validated? I'm thinking about something like this:
<div class="form-group">
<input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
<span class="error" ng-show="myInput.$error.maxlength">Too long!</span>
</div>
The example above doesn't work. Enclosing it in a <form> and replacing ng-show with ng-show="myForm.myInput.$error.maxlength" helps.
Is it possible to do this without using <form>?
You may use the ng-form angular directive (see docs here) to group anything, even outside a html form. Then, you can take advantage from angular FormController.
<div class="form-group" ng-form name="myForm">
<input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
<span class="error" ng-show="myForm.myInput.$error.maxlength">Too long!</span>
</div>
Example
Building on Silvio Lucas' answer, if you are iterating in a loop and need to be able to interpolate form names and valid states:
<div
name="{{propertyName}}"
ng-form=""
class="property-edit-view"
ng-class="{
'has-error': {{propertyName}}.editBox.$invalid,
'has-success':
{{propertyName}}.editBox.$valid &&
{{propertyName}}.editBox.$dirty &&
propertyValue.length !== 0
}"
ng-switch="schema.type">
<input
name="editBox"
ng-switch-when="int"
type="number"
ng-model="propertyValue"
ng-pattern="/^[0-9]+$/"
class="form-control">
<input
name="editBox"
ng-switch-default=""
type="text"
ng-model="propertyValue"
class="form-control">
<span class="property-type" ng-bind="schema.type"></span>
</div>
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script>
</head>
<body ng-controller="MainCtrl">
<div class="help-block error" ng-show="test.field.$error.required">Required</div>
<div class="help-block error" ng-show="test.firstName.$error.required">Name Required</div>
<p>Hello {{name}}!</p>
<div ng-form="test" id="test">
<input type="text" name="firstName" ng-model="firstName" required> First name <br/>
<input id="field" name="field" required ng-model="field2" type="text"/>
</div>
</body>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.field = "name";
$scope.firstName = "FirstName";
$scope.execute = function() {
alert('Executed!');
}
});
</script>

Resources