How to show error class when click button in AngularJs? - angularjs

How can I validate my form by click a button. Validation must be disabled when user typing into fields and must be enabled only when click button. How can I do this?
var app = angular.module("App",[]);
app.controller("Controller", function($scope){
$scope.Validate = function(){
if($scope.frm.$invalid){
alert("Form is invalid");
}
else{
alert("Form is valid");
}
};
});
input.ng-invalid:not(.has-focus) {
border:1px solid #ff7f7f;
background-color: #ffeeee;
}
<html ng-app="App">
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-controller="Controller">
<form name="frm">
<input type="text" ng-model="user.name" required/>
<input type="email" ng-model="user.email" required>
</form>
<a class="btn btn-info" ng-click="Validate()">Validate! </a>
</div>
</body>
</html>

required tag is from HTML5/browser validation, is not good practice use them, move all your validation to angularjs
so, to disable all browser validation (using novalidate tag)
<form name="frm" novalidate>
<input type="text" ng-model="user.name" />
<input type="email" ng-model="user.email" />
</form>
<a class="btn btn-info" ng-click="Validate()">Validate! </a>

I am all for the simplest answers possible. Why not just hide the validate button until you want them to see it?
What about ng-hide until all the fields have information, and then an ng-show once those conditions are met. Then you can do the ng-click statement that will validate the form?

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)"

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);
}

Why do we need ng-model in ng-form? [duplicate]

I am trying to use the angular form validations in my form for a blog post, and more specifically a ng-disabled form. For reasons I cannot figure out the submit button is not disabled, where as it should be unless all three input fields are valid. Thanks for the help.
this is my blog template
<div ng-controller='BlgoCtrl'>
<div class='container'>
<h1> Teewinot Blgo</h1>
<div class="row">
<div class='col-md-12'>
<form role='form' name='blgoPost' novalidate>
<div class='form-group'>
<label for='blgoTitle'>Title</label>
<input name='title' type="title" class='form-control' placeholder='Technologies of the Future' required><br>
<label for='blgoContent'>Content</label>
<textarea name='content' rows='8' type="content" class='form-control' placeholder='The technical innovations of the future will be diverse and impactful on the individual......' required></textarea><br>
<label for='blgoPassCode'>PassCode</label>
<input name='passcode' type="passcode" class='form-control' placeholder='•••••••••••••••' required><br>
<button type="submit" class='btn btn-primary' ng-disabled="blgoPost.$invalid">Submit Post</button>
</div>
</form>
</div>
</div>
Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Teewinot</title>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="bower_components/angular-route/angular-route.js"></script>
<link href="bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
</head>
<body ng-app="Teewinot">
<ng-include src="'app/templates/partials/navbar.html'"></ng-include>
<ng-view></ng-view>
<!-- angular module defintion and reoutes -->
<script src="app/js/app.js"></script>
<script src="app/js/routes.js"></script>
<!-- controllers -->
<script src="app/js/controllers/blog.controller.js"></script>
</body>
</html>
This is my blog controller
angular.module('Teewinot').controller('BlgoCtrl', function($scope, $http) {
'use strict'
});
You're missing ng-model on every field of your form. Keep in mind when you mention ng-model on any form field at that time ng-model creates the extra objects inside form name object with that specific name attribute which then considered while form validation like $error, $valid, $invalid, etc.
As your form name is blgoPost, when angular compile this page,it internally creates the object inside the scope of the name of blgoPost. And the all the input fields which has name & ng-model assign to them gets added inside that blgoPost object. But if you don't mention ng-model to the form fields then it will never get added inside the blgoPost form object.
HTML
<form role='form' name='blgoPost' novalidate="">
<input name="first" />
<div class='form-group'>
<label for='blgoTitle'>Title</label>
<input name='title' type="title" class='form-control' ng-model="test1" placeholder='Technologies of the Future' required="">
<br>
<label for='blgoContent'>Content</label>
<textarea name='content' rows='8' type="content" ng-model="test2" class='form-control' placeholder='The technical innovations of the future will be diverse and impactful on the individual......' required=""></textarea>
<br>
<label for='blgoPassCode'>PassCode</label>
<input name='passcode' type="passcode" ng-model="test3" class='form-control' placeholder='••&#8226' required="" />
<br/>
<button type="submit" class='btn btn-primary' ng-disabled="blgoPost.$invalid">Submit Post</button>
</div>
</form>
Working Fiddle

Why does this AngularJS code only work some of the time in Chrome? How do I fix it?

I'm trying to learn Google's "AngularJS" and having difficulty testing in Chrome browser. When I run the page in MSIE it works every time. In Chrome, one of two things happens: only part of the code works, or all of the code works.
I am aware of how to Disable the Chrome cache in Developer Tools, and to leave Developer Tools open while testing.
The "main.ctrl.js" file defines a Title for the page, which renders correctly. The code to update the Employee list only works some of the time. All of this works every time in MS Internet Explorer. Why? Why? Why!!!
app.js
angular.module('app', []);
main.ctrl.js
angular.module('app').controller("EmployeeController", function(){
var ec= this;
ec.title = 'Employee List';
ec.employees = [
{
firstName: "John",
lastName: "Doe",
office: "Washington D.C."
}];
ec.new = {};
ec.addEmployee = function() {
ec.employees.push(ec.new);
ec.new = {};
};
});
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>AngularJS Tutorial</title>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="main.ctrl.js"></script>
</head>
<body ng-app="app" ng-controller="EmployeeController as main">
{{main.title}}
<ul class="list-group">
<li class="list-group-item" ng-repeat="employee in main.employees">{{employee.firstName}} {{employee.lastName}}, {{employee.office}}</li>
</ul>
<form class="form" name="main.addForm" ng-submit="main.addEmployee()">
<div class="form-group">
<label>First Name <input class="form-control" ng-model="main.new.firstName" required type="text" /></label>
</div>
<div class="form-group">
<label>Last Name <input class="form-control" ng-model="main.new.lastName" required type="text" /></label>
</div>
<div class="form-group">
<label>Office <input class="form-control" ng-model="main.new.office" required type="text" /></label>
</div>
<div class="col-xs-6" style='align=center'>
<button class="btn btn-success"><label class="glyphicon glyphicon-plus-sign">Add</button>
</div>
</form>
</body>
</html>
The button in your form is not a submit button, it's just a regular button, which means the form doesn't know it's supposed to call the ng-submit function when you press it.
Try changing it to something like this and see if that works:
<input type="submit" id="submit" value="Submit" />

Resources