I am trying validate the textbox allow only integer number and greater than zero values.
Here I attached my code.
Html:
<body ng-app="myApp">
NUMBER ONLY <input type="text" allow-pattern="\d" />
</body>
Js:
var app = angular.module("myApp",[]);
app.directive('allowPattern', [allowPatternDirective]);
function allowPatternDirective() {
return {
restrict: "A",
compile: function(tElement, tAttrs) {
return function(scope, element, attrs) {
element.bind("keypress", function(event) {
var keyCode = event.which || event.keyCode; // I safely get the
if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) {
event.preventDefault();
return false;
}
});
};
}
};
}
Also I tried like this bellow:
<body ng-app="myApp">
NUMBER ONLY <input type="text" allow-pattern="^[1-9][0-9]*$" />
</body>
But its not working.
Check jsfiddle link: click here
You can make use of angular form validation and also use ng-model-options
Here is the link to Codepen
Controller snippet :
var app = angular.module('app',[]);
app.controller('myCtrl',function($scope){
$scope.onlyNumbers = /^[1-9]+[0-9]*$/;
})
View :
<div ng-app="app">
<br />
<br />
<div class="col-md-2" ng-controller="myCtrl">
<form name="myForm1">
<div class="form-group" ng-class="{'has-error':myForm1.number1.$invalid}">
<label for="">Following validation happens as the user entrs a value.</label>
<input class="form-control" ng-pattern="onlyNumbers" ng-model="value1" name="number1"/> Valid? {{myForm1.number1.$valid}}
</div>
</form>
<form name="myForm2">
<div class="form-group" ng-class="{'has-error':myForm2.number2.$invalid}">
<label for="">Following validation happens after blur </label>
<input class="form-control" ng-pattern="onlyNumbers" ng-model="value2" name="number2" ng-model-options="{ updateOn: 'blur'}"/> Valid? {{myForm2.number2.$valid}}
</div>
</form>
For more on how you can better this process through controllers refer this link
Related
I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>
https://jsfiddle.net/jzhang172/xu93yubL/
The particular issue is in my E-mail input field.
Is it possible to only display the ng-show message after the field is validated and when the user is not inside the input field?
In other words, I want the ng-show message to disappear if the user is on the input field.
I've tried a number of combinations of logic and haven't been able to get it to work:
(function(angular) {
'use strict';
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function(form) {
if (form) {
form.$setPristine();
form.$setUntouched();
}
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
})(window.angular);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form name="form" class="css-form" novalidate>
Name:
<input type="text" ng-model="user.name" name="uName" required="" />
<br />
<div ng-show="form.$submitted || form.uName.$touched">
<div ng-show="form.uName.$error.required">Tell us your name.</div>
</div>
E-mail:
<input type="email" ng-model="user.email" name="uEmail" required="" />
<br />
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required" style="background:red;">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email"style="background:red;">This is not a valid email.</span>
</div>
</form>
</div>
</body>
You can use ngFocus and ngBlur directives to achieve desired result...
Just set some variable false on ngFocus and set true with ngBlur and add that variable into your ngShow condition...
<input type="email" ng-model="user.email" name="uEmail" required="" ng-focus="showEmailValidationMsg = false;" ng-blur="showEmailValidationMsg = true;"/>
<br />
<div ng-show="(form.$submitted || form.uEmail.$touched) && showEmailValidationMsg">
<span ng-show="form.uEmail.$error.required" style="background:red;">Tell us your email.</span>
<span ng-show="form.uEmail.$error.email"style="background:red;">This is not a valid email.</span>
</div>
and here is working JSFIDDLE...
What I am trying to do is create a directive which compares two password inputs and triggers invalid if either changes. I have found a few examples and have tried a few and have combined a few in my own attempts. However, I have only been able to toggle the validity with $setValidity when the confirm password field changes. When you change the password field it doesn't trigger the invalidity of the comparison.
Here's my directive:
app.directive("passwordVerify", function() {
return {
require: "ngModel",
scope: {
passwordVerify: '=',
},
link: function(scope, element, attrs, ctrl) {
scope.$watch(function() {
var combined;
if (scope.passwordVerify || ctrl.$viewValue) {
combined = scope.passwordVerify + '_' + scope.$view;
}
return combined;
}, function(value) {
if (value) {
ctrl.$parsers.unshift(function(viewValue) {
var origin = scope.passwordVerify;
if (origin !== viewValue) {
ctrl.$setValidity("pwd", false);
return undefined;
} else {
ctrl.$setValidity("pwd", true);
return viewValue;
}
});
}
});
}
};
});
Here's the directive in action:
<input id="user_password" type="password" name='user_password' placeholder="password" value='' required ng-model="user.user_password">
<p class="help-text">Required</p>
<div class="help-block" ng-messages="add_user_form.user_password.$error" ng-show="add_user_form.user_password.$touched">
<div ng-messages-include="/app/views/messages.html" ></div>
<input id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" name="user_confirm_password" required password-verify="user.user_password">
<p class="help-text">Enter matching password</p>
<div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-show="add_user_form.confirm_password.$touched">
<div ng-messages-include="/app/views/messages.html" ></div>
With this code I can verify that the passwords match when I change the value of the confirm password field, however when you change the value of the password field it doesn't revalidate the input. I'm pretty sure there is a successful way to add $watch to two elements or to use $watchgroup to do this. I just can't figure it out. I know there are a lot of questions on this topic but all I've tried have only gotten me to this point.
I'm using Angular 1.5.7 btw...
Here's a version working bi-directionally:
(function() {
"use strict";
angular.module('app', ['ngMessages'])
.controller('mainCtrl', function($scope) {
})
.directive('passwordVerify', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, elem, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// watch own value and re-validate on change
scope.$watch(attrs.ngModel, function() {
validate();
});
// observe the other value and re-validate on change
attrs.$observe('passwordVerify', function(val) {
validate();
});
var validate = function() {
// values
var val1 = ngModel.$viewValue;
var val2 = attrs.passwordVerify;
// set validity
ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);
};
}
}
})
})();
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.7/angular-messages.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<form name="add_user_form">
<div class="col-md-12">
<div class="form-group" ng-class="{ 'has-error' : add_user_form.user_password.$touched && add_user_form.user_password.$invalid }">
<p class="help-text">Enter password</p>
<input type="password" class="form-control" id="user_password" name="user_password" placeholder="password" required ng-model="user.user_password" password-verify="{{user.confirm_password}}">
<div class="help-block" ng-messages="add_user_form.user_password.$error" ng-show="add_user_form.user_password.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
<p ng-message="required">This field is required</p>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error' : add_user_form.confirm_password.$touched && add_user_form.confirm_password.$invalid }">
<p class="help-text">Enter matching password</p>
<input class="form-control" id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" required password-verify="{{user.user_password}}">
<div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-show="add_user_form.confirm_password.$touched">
<p ng-message="required">This field is required</p>
<p ng-message="minlength">This field is too short</p>
<p ng-message="maxlength">This field is too long</p>
<p ng-message="required">This field is required</p>
<p ng-message="passwordVerify">No match!</p>
</div>
</div>
</div>
</form>
</body>
</html>
I hope it helps.
So I am trying to auto submit the form once it has been validated.
HTML
<form name="myForm" role="form" novalidate>
<div class="form-group">
<select class="form-control" name="location" ng-model='calc.location1' required>
<option value=7>Location1</option>
<option value=9>Location2</option>
<option value=5>Location3</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type='number' name="Size" ng-model='calc.Size' placeholder="Sq ft" required>
</div>
<div class="form-group">
<input class="form-control" type='number' name="units" ng-model='calc.units' placeholder="Units in kWH" required>
</div>
</form>
Controller
myapp.controller('demoController', ['$scope', function($scope, $document) {
$scope.$watch('myForm.units.$valid', function (newValue, oldvalue){
if(newValue) {
console.log(newValue);
}
})
}])
I want to insert my form submit code inside the if statement, but newValue is always showing true even when the form inputs are empty at page load.
Trying to do something like this http://jsfiddle.net/cmyworld/EdCEW/ but no idea where I am going wrong.
The Solution is to create one method to validate all fields and set scope variable to true if all fields are valid.
var app = angular.module('myApp', []);
app.controller('myController',['$scope',function($scope) {
$scope.checked = 0;
$scope.$watch('myForm.$valid', function (newValue, oldvalue){
$scope.checkDirty();
if($scope.checked === 1)
{ alert('Model is valid');
//Can do a ajax model submit.
}
});
$scope.checkDirty = function(){
if($scope.myForm.Size.$valid && $scope.myForm.units.$valid)
{
$scope.checked = 1;
}
else
{
$scope.checked =0;
}
};
}]);
Here is the example http://jsfiddle.net/EdCEW/92/
I am trying to use angular's form validation from inside a templateUrl.
I have a directive that loads a templateUrl in which i have a form with inputs that get ng-required and ng-regex values from directive scope. Now, i tried to put in my directive's scope
form: '=', but when i access scope.form it is undefined.
I must specify that my submit button is outside of the form, and when clicked ng-click='save($index)' it must first check that the form is valid and then proceed with saving the edited data. scope.save() is defined in my directive.
this is from template:
<tr data-ng-repeat="row in source.data " data-ng-class="{'selected':row.$_selected}" >
<td data-ng-repeat="c in settings.columns" data-ng-click="toggleSelect(row)" >
<form name="editForm" id="editForm" novalidate>
<div ng-switch on="c.type" ng-show="editMode[$parent.$index]">
<span ng-switch-when="text" >
<input type="{{c.type}}" data-ng-model="row[c.name]" ng-required="{{c.isRequired}}" ng-pattern="{{c.regex}}"/>
</span>
<span ng-switch-when="select" >
<select data-ng-model="row[c.name]" ng-selected="row[c.name]" ng-init="row[c.name]" ng-options="item.value as item.name for item in c.items" ng-required="{{c.isRequired}}">
<!--<option data-ng-repeat="(value, name) in c.items" value="{{value}}">{{name}}</option>-->
</select>
</span>
<span ng-switch-when="textarea">
<textarea ng-model="row[c.name]" ng-required="{{c.isRequired}}" ng-pattern="{{c.regex}}">
</textarea>
</span>
<span ng-switch-when="checkbox">
<!--<label for="checkboxInput">{{c.name}}</label>-->
<input name="checkboxInput" type="checkbox" data-ng-model="row[c.name]" ng-true-value="{{c.true}}" ng-false-value="{{c.false}}"/>
</span>
<span ng-switch-default="">
{{row[c.name]}}
</span>
</div>
</form>
<span ng-hide='editMode[$parent.$index]'>{{row[c.name]}}</span>
</td>
<td>
<a href="{{row[settings.specialFields.url]}}" class="btn btn-default opacity75" data-ng-if="row[settings.specialFields.url]">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</td>
<td data-ng-if="row[settings.specialFields.isEditable]">
<button ng-click="edit(row)" ng-show="!editMode[$index]" class="btn btn-primary" >
edit {{$index}}
</button>
<button ng-click="save($index)" ng-disabled="" ng-show="editMode[$index]" class="btn btn-primary">
save
</button>
<button ng-click="cancel($index)" ng-show="editMode[$index]" class="btn btn-default">
cancel
</button>
</td>
</tr>
and this is from my directive:
scope: {
settings: '=',
source: '=',
form: '='
},
templateUrl: function (element, attr) {
return attr.templateUrl || 'src/grid.html';
},
link: function (scope, element, attrs) {
scope.editMode = [];
scope.editing = false;
scope.previousData = {};
scope.edit = function(field) {
scope.editing = scope.source.data.indexOf(field);
scope.editMode[scope.editing] = true;
scope.previousData = angular.copy(field);
};
scope.save = function(index){
console.log(scope.form);
scope.editMode[index] = false;
if (scope.editing !== false ) {
//do the saving
scope.editing = false;
}
};
scope.cancel = function(index){
scope.editMode[index] = false;
if (scope.editing !== false) {
scope.source.data[scope.editing] = scope.previousData;
scope.editing = false;
}
}
Here you go:
Working Form
Form button is outside of form, and could also be outside of directive. It doesn't matter with Angularjs.
There are two inputs, both have required and both have regex validation as you stated.
There is a directive with a templateURL
The important thing to remember here is that the form must have a name, and then it is referenced by that name as in: scope.myForm when
You don't have to name the input fields as I did in the plunker, but if you do, and they are ALL different values from one another, then you can do this: scope.myForm.myInputName.$valid to see if each input is valid if you wished.
But, the actual form will not be valid until ALL the inputs are valid, so you probably just need to call valid on the form itself as in in the provided example.
If you move the button outside of the directive, you will have to move the submit function from the directive to the controller (most likely).
Let me know if this helps, I can change things if needed. Also, try the plunker first with your question, then post what's going on with that new code; just fork the plunker and provide a link.
Here is the plunker code just in case...
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap#*" data-semver="3.2.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" />
<script data-require="jquery#*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>
<script data-require="angular.js#1.3.7" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script data-require="angular-ui-bootstrap#0.12.0" data-semver="0.12.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<my-directive></my-directive>
</div>
</div>
</html>
<form name="myForm" novalidate>
<label>Input #1 (required)</label><br>
<input ng-model="form.data.myName" name='myName' ng-pattern="/\D+/" ng-required="true" /> <span ng-show="myForm.myName.$error.pattern">Takes anything but digits</span><br>
<br>
<label>Input #2 (required)</label><br>
<input ng-model="form.data.myEmail" name='myEmail' ng-pattern="/\d+/" ng-required="true" /> <span ng-show="myForm.myEmail.$error.pattern">Takes only digits</span>
</form>
<br>
<p># I'm a button that is outside of the form!</p>
<p ng-model="form.submitted">Form Submitted: <span class="blue">{{ form.submitted }}</span></p>
<p>Form Valid?: <span class="blue">{{ myForm.$valid }}</span></p>
<button ng-click="submitForm('myForm')">Submit Form</button>
<p ng-model="form.data">Here is the Form data:</p>
{{ form.data }}
var app = angular.module('myApp', []);
app.controller('MyCtrl', function ($scope) {});
app.directive("myDirective", function () {
return {
restrict: 'AE',
require: '?ngModel',
templateUrl: 'my-directive.html',
link: function (scope, elm, attrs, ctrl) {
scope.form = {submitted: false, data: {}};
scope.submitForm = function(formname){
console.log(scope[formname].myEmail)
console.log(scope.formname)
console.log(scope[formname].$valid)
scope.form.submitted = true;
}
} // end link
} // end return
});