better custom validation for angular form - angularjs

I searched, I know 'the directive way' to do custom validation, but it looks like a overkill to me, I hope there is a simpler way, so I tried somwthing like this.
it works, but really not sure it is the right way(or angular way).
.controller('vali', ['$scope', function vali($scope) {
var th = this
th.formData = {}
// watch password repeat
$scope.$watch(function() {
return th.password1
}, function(newPass) {
if(!customValidate(newPass)) th.form.pass2.$setValidity('custom', false)
else th.form.pass2.$setValidity('custom', true)
})
//custom validate: password repeat must equal to password
function customValidate(v) {
if(v === th.formData.password) return true
else return false
}
this.submit = function(form) {
if(!th.form.$invalid) th.postToServer(th.formData)
}
this.postToServer = function(data) {
//do post to server
console.log(data)
}
}])
html:
<div ng-controller='vali as v'>
<form name='v.form' ng-submit='v.submit'>
<input type='password' name='pass1' ng-model='v.formData.password' minlength='6' />
<input type='password' name='pass2' ng-model='v.password1' />
<div ng-messages='v.form.pass2.$error' ng-if='v.form.pass2.$dirty'>
<div ng-message='required'>required</div>
<div ng-message='custom'> not equal</div>
</div>
<button type='submit'>submit</button>
</form>
</div>

You don't need to create your own directive for this. There is already a built-in directive for the password validation.
You can use that like this :
<input name="password" required ng-model="password">
<input name="confirm_password"
ui-validate=" '$value==password' "
ui-validate-watch=" 'password' ">
The input will be valid when the expression in ui-validate is true, so you can have any validation you want by changing the expression.

Related

AngularJS error: TypeError: v2.login is not a function

I would like to call the login function when I click the login button but keep getting the error message in the title. Can someone point out the error in my script?
login.js code below:
/*global Firebase, angular, console*/
'use strict';
// Create a new app with the AngularFire module
var app = angular.module("runsheetApp");
app.controller("AuthCtrl", function ($scope, $firebaseAuth) {
var ref = new Firebase("https://xxxxx.firebaseio.com");
function login() {
ref.authWithPassword({
email : "xxxxx",
password : "xxxx"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
And the code for login.html is also below:
<div class="container" style="max-width: 300px">
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
</div>
Edge case here, but I want to mention it for posterities' sake. I got this same error when using the controllerAs pattern with a form name with the same value as ng-submit. For example:
<form name="authCtrl.signUp" ng-submit="authCtrl.signUp()">
Throws: TypeError: v2.signUp is not a function
The solution was to change the name of the form to something different:
<form name="authCtrl.signUpForm" ng-submit="authCtrl.signUp()">
In my case, I was having an exact same issue as yours. However, coming across gkalpak's answer to such a scenario helped me out.
Turned out to be what I was calling was addBuddy() function, from a form named "addBuddy". The solution was to change the name of either of the two things to make one stand out or differentiable from the other. I changed the name of the form to "addBuddyForm" and voila! My function worked!
Here's a snippet of my case:
<form name="addBuddy" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
Which, I changed to:
<form name="addBuddyForm" class="form-horizontal" novalidate>
...
<button class="btn btn-sm btn-info" ng-click="addBuddy()>Submit</button>
...and it worked! :)
In AngularJS call the function from view it must be in the $scope.
JS
// exposes login function in scope
$scope.login = login;
HTML
<div class="container" ng-controller="AuthCtrl" style="max-width: 300px"> <!-- I notice here for include ng-controller to your main div -->
<form class="form-signin">
<h2 class="form-signin-heading" style="text-align: center">Please Sign In</h2>
<input type="text" class="form-control" name="username" ng-model = "username" placeholder="Email Address" required="" autofocus="" />
</br>
<input type="password" class="form-control" name="password" ng-model = "password" placeholder="Password" required=""/>
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="login()">Login</button>
</form>
This may not be specific to your problem, but I was also getting this error and it took a bit to figure out why.
I had named both a function and a variable the same, with the variable assigned in the function, and so the assignment of the variable was overriding the function and it was exploding on a second run.
You'll notice in the example the uploadFile() function as an upload.uploadFile = true; This was a wonderful file that was meant to be upload.uploadingFile - a flag used to control the behavior of a spinner. Once that was fixed, the issue went away.
Example:
(function()
{
'use strict';
angular.module('aumApp.file-upload')
.controller('FileUploadCtrl', FileUploadCtrl);
function FileUploadCtrl($scope, $http)
{
upload.uploadFile = function()
{
upload.uploadFile = true;
var backendUrl = '/ua_aumcore/events/api/v1/events/uploadFile';
var fd = new FormData();
fd.append('file', upload.src);
$http({ url: backendUrl, data: fd, method: 'POST', transformRequest : angular.identity, headers: { 'Content-Type' : undefined } })
.then(function uploadSuccess(response)
{
upload.data = response.data;
upload.message = "Uploaded Succesfully.";
upload.uploadSuccess = true;
upload.uploadingFile = false;
},
function uploadFailure(response)
{
upload.message = "Upload Failed.";
upload.uploadSuccess = false;
upload.uploadingFile = false;
});
};
}
FileUploadCtrl.$inject = ['$scope', '$http'];
})();
To be callable from the view, a function must be in the $scope. Add
$scope.login = login;
to the JS code of the controller.
You also need to actually use that controller. Change
<div class="container" style="max-width: 300px">
to
<div ng-controller="AuthCtrl" class="container" style="max-width: 300px">
This is all fundamental stuff. My advice would be to learn from an AngularJS tutorial before going further.
Two enable two-way binding you have to assign your login function to $scope. Replace your code for function with this:
$scope.login=function() {
ref.authWithPassword({
email : "nick.koulias#gmail.com",
password : "Jaeger01"
}, function (error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
});
}
It may be a late answer by me.
But It working for me
Check form name you set
e.g. ng-form="login"
and function name
e.g. ng-click="login()"
Then it will not work . You have to change one of them.
e.g. ng-form="loginForm"
Explanation:
AngularJS 1.x registers any form DOM element that has a name property in $scope via formDirectiveFactory. This directive automatically instantiates form.FormController if the above is true:
If the name attribute is specified, the form controller is published onto the current scope under
from: angular.js:24855
Hence if you have a <form name=myForm> it will override your $scope.myForm = function() { ... }

Cannot read property $valid of undefined

I have a form like this -
<form name="myForm" novalidate>
There are some fields in the form which I am validating and then submitting the form like this -
<input type="button" ng-click="Save(data)" value="Save">
In the controller, I want to check if the form is not valid then Save() should show some error on the page. For that, I am setting up a watch like this -
$scope.$watch('myForm.$valid', function(validity) {
if(validity == false)
// show errors
});
But I am always getting this error on running it -
Cannot read property '$valid' of undefined
Can someone explain why?
Thanks
You just misspelled "myForm" in your controller code. In order to remove the error, Write "myform" instead of "myForm".
However I expect what you want is like this.
$scope.Save = function(data){
alert($scope.myform.$valid);
}
I setup jsfiddle.
In my case I was wrapping the form in a modal created in the controller and therefore got the same error. I fixed it with:
HTML
<form name="form.editAddress" ng-submit="save()">
<div class="form-group">
<label for="street">Street</label>
<input name="street" type="text" class="form-control" id="street" placeholder="Street..." ng-model="Address.Street" required ng-minlength="2" />
<div class="error" ng-show="form.editAddress.street.$invalid">
<!-- errors... -->
</div>
</div>
<button type="submit" class="btn btn-primary" >Save address</button>
</form>
JS
angular.module("app").controller("addressController", function ($scope, $uibModal, service) {
$scope.Address = {};
$scope.form = {};
$scope.save = function() {
if (modalInstance !== null) {
if (isValidForm()) {
modalInstance.close($scope.Address);
}
}
};
var isValidForm = function () {
return $scope.form.editAddress.$valid;
}
});

Adding hidden form field to array in Angular

I am trying to add a "hidden" field to a basic form in Angular (using Firebase as the backend). I'm having trouble figuring out how to include this field as part of the array when the form is submitted. I want to include {type: 'Basic'} as part of the array. I've looked at the other related posts on this site, but am still unsure how to apply to my particular situation.
Any suggestions on how to do this?
Javascript:
myApp.controller('NewProjectCtrl', function ($location, Projects) {
var editProject = this;
editProject.type = 'Basic'; //this is the hidden field
editProject.save = function () {
Projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
});
HTML:
<form>
<div class="control-group form-group">
<label>Name</label>
<input type="text" name="name" ng-model="editProject.project.name">
</div>
<label>Description</label>
<textarea name="description" class="form-control" ng-model="editProject.project.description"></textarea>
<button ng-click="editProject.save()" class="btn btn-primary">Save</button>
</form>
You don't need a hidden form field, just submit your value in your controller like this:
editProject.save = function () {
editProject.project.type = 'Basic';
Projects.$add(editProject.project).then(function(data) {
$location.path('/');
});
};
All attributes of your editProject.project will be submitted, as you may notice in the developer console.
I would structure the controller a bit different.. here is an example (I am considering you are using angular-resource, where Projects returns a Resource?):
myApp.controller('NewProjectCtrl', function ($location, Projects) {
$scope.project = new Projects({type: 'Basic'});
$scope.save = function () {
$scope.project.$save().then(function(data) {
$location.path('/');
});
};
});
<form ng-submit="save()">
<div class="control-group form-group">
<label>Name</label>
<input type="text" name="name" ng-model="project.name">
</div>
<label>Description</label>
<textarea name="description" class="form-control" ng-model="project.description"></textarea>
<input type="submit" value="Save" class="btn btn-primary" />
</form>
The save function will $save the new project resource (this is an default method and will make a POST on the given resource URL).

Angular seed, where is the function variable coming from?

There is an Angular seed using Firebase and AngularFire on github form the Firebase team that I am trying to understand how works. The login page looks like this:
<form>
<label>
<span>email</span>
<input type="text" ng-model="email" />
</label>
<label>
<span>password</span>
<input type="password" ng-model="pass" />
</label>
<label ng-cloak ng-show="createMode">
<span>confirm pass</span>
<input type="password" ng-model="confirm" />
</label>
<button ng-click="login()" ng-hide="createMode">Log In</button>
<button ng-click="createMode = true" ng-hide="createMode">Register</button>
<button ng-cloak ng-show="createMode" ng-click="createAccount()">Create Account</button>
<button ng-cloak ng-show="createMode" ng-click="createMode = false">Cancel</button>
<p ng-show="err" class="error">{{err}}</p>
</form>
And the controller for the login-function looks like this:
$scope.login = function(cb) {
$scope.err = null;
if( !$scope.email ) {
$scope.err = 'Please enter an email address';
}
else if( !$scope.pass ) {
$scope.err = 'Please enter a password';
}
else {
loginService.login($scope.email, $scope.pass, function(err, user) {
$scope.err = err? err + '' : null;
if( !err ) {
cb && cb(user);
}
});
}
The view calls the login function like this: login(), but in the controller the function definition starts like this $scope.login = function(cb) and then cb is used in the function. But the function is never called with any variable/object, so what is happening with cb here?
The parameter is not used when calling login function from the template, but if you look at $scope.createAccount function definition in the controller, it calls the same $scope.login function, but with defined callback parameter

Show informative message when the modal is focused

<input type="text" ng-model="user.username" name="username" required>
<div class="sidetip">
<div ng-show="signup.username.$pristine">
<span>Choose a Username.</span>
</div>
I only want to show the "Choose a Username", If the form is pristine AND the input "username" is focused. How can I accomplish that?
The ng-focus seems like I only can apply on the input, and not what I am asking for "When the Input username is active, display this is if form username also is pristine"...
Something like this would work?
Here is a demo
<form name='signup' ng-submit="submit()" ng-controller="Ctrl">
Username:
<input type="text" ng-model="user.username" name="username" ng-focus="usernameIsFocus=true" ng-blur="usernameIsFocus=false" required />
<div class="sidetip">
<div ng-show="signup.username.$pristine && usernameIsFocus">
<span>Choose a Username. Click outside text field to hide this tip.</span>
</div>
</div>
</form>
just a side note
signup.username.$pristine
is not the same as
user.username == ''
so if you enter text in input username and then delete it, the first will be false and the second will be true
Angular 1.2 has ngBlur and ngFocus directives, in older versions you can create a directive which changes value given variable on focus is-focus="usernameIsFocus"
<input type="text" ng-model="user.username" name="username" required is-focus="usernameIsFocus">
<div class="sidetip">
<div ng-show="usernameIsFocus">
<span>Choose a Username.</span>
</div>
</div>
directive
app.directive('isFocus', function(){
return {
scope: {
isFocus: '='
},
link: function(scope, element, attrs){
element.on('focus', function() {
scope.$apply(function () {
scope.isFocus = true;
});
});
element.on('blur', function() {
scope.$apply(function () {
scope.isFocus = false;
});
});
}
};
});
Here a working example:
http://plnkr.co/edit/Xan0rO8FKeOAlFC2MwoO?p=preview

Resources