Angular custom form validation - javascript

I was trying to follow some tutorials, but couldn't figure out what to do.
I would like to add the validation, that at least one of the checkboxes (consumer/vendor) has to be true. If not true show an error message at both fields). What would be the easiest way to accomplish that?
<form role="form" name="addClientForm" ng-submit="submitForm(addClientForm.$valid)" novalidate>
<div class="form-group" ng-class="{ 'has-error' : addClientForm.title.$invalid && !addClientForm.title.$pristine }">
<label>Title</label>
<input type="text" class="form-control" placeholder="Enter a title" ng-model="client.title" required>
</div>
<div class="form-group" ng-class="{ 'has-error' : addClientForm.company.$invalid && !addClientForm.company.$pristine }">
<label>Company</label>
<input type="text" class="form-control" placeholder="Enter a company" ng-model="client.company" required>
</div>
<div class="checkbox">
<label class="i-checks">
<input type="checkbox" ng-model="client.consumer"><i></i> Consumer
</label>
</div>
<div class="checkbox">
<label class="i-checks">
<input type="checkbox" ng-model="client.vendor"><i></i> Vendor
</label>
</div>
</form>
Controller (modal controller)
angular.module('App')
.controller('ModalAddClientCtrl', function ($scope, $modalInstance) {
$scope.client = { title: '', company: '', consumer: true, vendor: false };
$scope.submitForm = function(isValid) {
};
$scope.ok = function () {
$modalInstance.close($scope.client);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});

To use angular form validation like you are trying to you have to set name attribute in the input fields. So, if you have a <form name='form'> with <input name='input'> only then you can use form.input.$dirty or form.input.$pristine. Combine that with ng-if like you have the rest is simple.
See this fiddle for example and try editing the values. I have implemented validation in your form. I have left out the controller, conditions and error messages could be simpler but you will get the idea.
See this related post that has an excellent answer on using form validation.

Related

How to validate template driven form without model driven approach.?

I am trying to validate template driven form in Angular without two way databinding. I have done validation using [(ngModel)] but when i try to validate form without MODEL i get following error
Cannot read property 'invalid' of undefined
This is my HTML code.
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular 6 Template-Driven Form Validation</h3>
<form name="form" (ngSubmit)="onSubmit(f.value)" #f="ngForm" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text"
class="form-control"
name="username"
#userName
required
minlength="8"/>
<div *ngIf="f.form.controls.username.invalid && f.form.controls.username.touched" class="invalid-feedback">
<div *ngIf="f.form.controls.username.errors.required" class="alert alert-danger">Username is required</div>
<div *ngIf="f.form.controls.username.minlength" class="alert alert-danger">length should b 8 character</div>
</div>
</div>
<button class="btn btn-primary" >Register</button>
</form>
</div>
</div>
</div>
</div>
It also not sending data to component when i click button.
this is component TS file .
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-template-driven-form',
templateUrl: './template-driven-form.component.html',
styleUrls: ['./template-driven-form.component.css']
})
export class TemplateDrivenFormComponent {
// model: any = {};
onSubmit(f) {
// alert('SUCCESS!! :-)\n\n' + f);
console.log(f);
}
}
Just replace:
f.form.controls.username.invalid
with
username.invalid
but its mandatory to use ngModel
so your HTML control:
<input type="text" ngModel class="form-control" name="username" #username="ngModel" required minlength="8"/>
It's not working because it shouldn't.
As you can see, inputs that aren't bound with ngModel aren't part of your form.
So simply use ngModel and you should be good to go.

AngularJS with ng-pattern in form does not send invalid field to server

I want to validate a text input in form, so the submit of the form could not be done until the input match a regular expression. But when I type a wrong field value and I clik submit the form is submitted but the input value is not sent to the server. I want the same behaviour as with HTML5 required Attribute. This is my code:
<div class="row">
<label class="col-sm-2 label-on-left">APN</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="apn" ng-model="Configure3gCtrl.configure3g.apn" ng-pattern="/^[a-zA-Z0-9-.]*$/" required/>
</div>
</div>
</div>
As i said in the comment [value not sent because when you pass the input with incorrect pattern the ng-model is undefined].
But we can use the form validation here as sample if our ng-model are invalid the form will disabled.
var app = angular.module("app", []);
app.controller("ctrl", ["$scope", "$filter", function($scope, $filter) {
$scope.submit = function() {
console.log($scope.object)
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form name="form">
<label class="col-sm-2 label-on-left">APN</label>
<input type="text" name="apn" ng-model="object.apn" ng-pattern="/^[a-zA-Z0-9-.]*$/" required />
<button ng-click="submit()" ng-disabled="form.$invalid">submit</button>
</form>
</div>
Ideally, you should not send the invalid value to server, So you should disable\hide your submit button, but if you really require sending the invalid value as well to server, then from angularjs 1.3+ you have ng-model-options (Read Doc) directive which can help you.
Simply mark your text type input as ng-model-options="{allowInvalid: true }", It will persist the invalid values as well.
See Demo:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function MyCtrl($scope) {
$scope.submitt = function() {
alert($scope.Configure3gCtrl.configure3g.apn);
}
$scope.Configure3gCtrl = {
configure3g: {
apn: ""
}
}
});
<script src="https://code.angularjs.org/1.3.1/angular.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="frm" ng-submit="submitt()" class="row">
<label class="col-sm-2 label-on-left">APN</label>
<div class="col-sm-7">
<div class="form-group label-floating">
<label class="control-label"></label>
<input class="form-control" type="text" name="apn"
ng-model="Configure3gCtrl.configure3g.apn"
ng-model-options="{allowInvalid: true }"
ng-pattern="/^[a-zA-Z0-9-.]*$/" required/>
</div>
</div>
<input type="submit" value="submit" type="submit" />
</form>
</div>
also, Test with removing ng-model-options="{allowInvalid: '$inherit' }" from above code snippet then ng-model will be undefined, because it is invalid.

Custom password validation directive not applying

I'm working with AngularJS and I want to make a password confirmation field to check if both entries match. In order to do that, I'm using a custom directive from this tutorial: http://odetocode.com/blogs/scott/archive/2014/10/13/confirm-password-validation-in-angularjs.aspx.
For some reason, the matching checking doesn't give any result. When I enter different passwords, it still sees the fields as valid. I think I'm missing something about the usage of custom directives in AngularJS, but it's a bit confusing because I'm litterally taking the exact same code as in the tutorial.
I also checked related questions here on SO, but no luck either.
HTML:
<div ng-app="myApp">
<h1>Register!</h1>
<form name="registrationForm" novalidate>
<div class="form-group">
<label>User Name</label>
<input type="text" name="username" class="form-control" ng-model="registration.user.username" required />
<p ng-show="registrationForm.username.$error.required">Required<br/><br/></p>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" ng-model="registration.user.password" required />
<p ng-show="registrationForm.password.$error.required">Required<br/><br/></p>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirmPassword" class="form-control" ng-model="registration.user.confirmPassword" required compare-to="registration.user.password" />
<p ng-show="registrationForm.confirmPassword.$error.required">Required<br/><br/></p>
<p ng-show="registrationForm.confirmPassword.$error.compareTo">Passwords must match !</p>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register!</button>
</div>
</form>
</div>
JS:
angular.module('myApp', [])
.directive('compareTo', function(){
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
};
})
JSFiddle showing the problem: http://jsfiddle.net/ptb01eak/
Working Plunkr from the tutorial: http://plnkr.co/edit/FipgiTUaaymm5Mk6HIfn?p=preview
Thank you for your help!
The problem comes from your AngularJS version, I updated it in the jsfiddle to : AngularJS 1.5.6 (CDN link) and it works (new jsfiddle).

I can't access ng-model from a controller [AngularJS]

I'm developing an e-commerce site for learnign purposes.
HTML:
<div class="container">
<form class="log-in-form" ng-controller="ControllerLogin">
<div class="form-group">
<label for="loginEmail">Email address</label>
<input type="email" class="form-control" id="loginEmail" placeholder="Email" ng-model="email">
</div>
<div class="form-group">
<label for="loginPass">Password</label>
<input type="password" class="form-control" id="loginPass" placeholder="Password" ng-model="password">
</div>
<button class="btn btn-default" ng-click="authenticate()">Login</button>
</form>
</div>
Angular javascript
app.controller('ControllerLogin', ['$scope', '$http', 'ServiceLogin', function ($scope, $http, ServiceLogin) {
$scope.authenticate = function () {
console.log($scope.email);
ServiceLogin.auth($scope.email, $scope.password)
.success(function (data) {
alert(data);
});
}
}]);
Every time I console.log the $scope.email, or password. It throws an error of undefined. I'm just starting on angular and I don't know why is not getting the models, I thinks my code is correct. Any help you can give I will be gratefull.
From Angular site:
Note that novalidate is used to disable browser's native form validation.
The value of ngModel won't be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user#domain.
Reference: https://docs.angularjs.org/guide/forms
So the reason it may be blank is that it's not a valid email.
You can look at their demo for the email type and see it in action.
I recommend adding:
{{email}}
<br>
{{password}}
somewhere in your html within the controller's HTML scope for your own debugging.
Good luck.

How to set the value of an option when using ng-options in controller?

I am getting customer for given id,Customer details are name, email and type of customer {0,1}. For 0, customer will be Regular and 1 will Temporary.
I am able to show details of customer on form but but able to select the type of customer. My select options are showing {'regular', 'temporary'}, but not select any option value.
For example
customer1={'name':'john', 'email':'john#gmail.com', 'customer_type':0}
Form is able to show name and email but not selecting 'regular' options
Controller
$scope.customers_type=['regular','temporary'];
//I will get details of customer
$scope.customer=getCustomer($scope.id);
if($scope.customer.customer_type ==0)
$scope.customer.type=$scope.customers_type[0]
else
$scope.customer.type=$scope.customers_type[1]
HTML
<div>
<label for="Name">Name </label>
<input ng-model='customer.name' name="Name" type="text">
</div>
<div>
<label for="email">Email </label>
<input ng-model='customer.email' name="email" type="text">
</div>
<div>
<label for="enterprise">Type of type of Customer </label>
<select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
</select>
</div>
Code is working fine without any error for angularjs 1.2.23
Just have replaced getCustomer method to object.
If it is not working then Check customer object using breakpoint and check whether it's proper or not and also check which version of angularjs you are using.
angular.module("myApp", []).controller('MyContrl', function($scope) {
$scope.customers_type = ['regular', 'temporary'];
//I will get details of customer
$scope.customer = {
'name': 'john',
'email': 'john#gmail.com',
'customer_type': 0
};
if ($scope.customer.customer_type === 0) {
$scope.customer.type = $scope.customers_type[0]
} else {
$scope.customer.type = $scope.customers_type[1]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyContrl">
<div>
<label for="Name">Name</label>
<input ng-model='customer.name' name="Name" type="text">
</div>
<div>
<label for="email">Email</label>
<input ng-model='customer.email' name="email" type="text">
</div>
<div>
<label for="enterprise">Type of type of Customer</label>
<select ng-model='customer.type' type="text" ng-options="type for type in customers_type">
</select>
</div>
</div>
I think you need to specify ng-selected and set it to your current customer type.
If you don't specify ng-selected you'll end up with 3 options: '', 'regular', 'temporary'

Categories