Related
How to disable special characters in angular js input tag. Only allow alphanumeric
just like we use
<input type="text" ng-trim="false" style="text-transform: uppercase" ng-pattern="/^[a-zA-Z0-9]*$/" class="form-text" id="pan_card_number" name="pan_card_number" ng-minlength="10" maxlength="10" required ng-model="registration.newTSP.panCardNumber">
you can use Regex with Ng-pattern and Display the message through ng-message
$scope.useOnlySpecialCharacters = /^[a-zA-Z0-9]*$/;
<input type="text" ng-model="specialcharacters"
ng-pattern="useOnlySpecialCharacters" />
show message through ng-message
<div ng-message="pattern"> Please Enter AlphaNumeric </div>
OR
Best Option is to use Directives
app.directive('noSpecialChar', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == null) {
return '';
}
var cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
LINK
use ng-pattern="/[A-Z]{5}\d{4}[A-Z]{1}/i" in your HTML input tag
use the following
Controller
$scope.panCardRegex = '/[A-Z]{5}\d{4}[A-Z]{1}/i';
HTML
<input type="text" ng-model="abc" ng-pattern="panCardRegex" />
Use Directives to restrict Special characters:
angular.module('scPatternExample', [])
.controller('scController', ['$scope', function($scope) {
}])
.directive('restrictSpecialCharactersDirective', function() {
function link(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
var reg = /^[a-zA-Z0-9]*$/;
if (viewValue.match(reg)) {
return viewValue;
}
var transformedValue = ngModel.$modelValue;
ngModel.$setViewValue(transformedValue);
ngModel.$render();
return transformedValue;
});
}
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
<input type="text" ng-model="coupon.code" restrict-Special-Characters-Directive>
set pattern to allow only alphanumeric
/^[a-z0-9]+$/i
I am using the following code to get the "auto tab" working with AngularJS (automatically tabs the user to the "Title" textbox after the max length is met for the "Name" textbox):
var app = angular.module('plunker', []);
app.directive('autoTabTo', [function () {
return {
restrict: "A",
link: function (scope, el, attrs) {
el.bind('keyup', function(e) {
if (this.value.length === this.maxLength) {
var element = document.getElementById(attrs.autoTabTo);
if (element)
element.focus();
}
});
}
}
}]);
Here is my HTML (with my custom directives):
<customtextfield autoTabTo="Variant.Specs.Title" ng-maxlength="20" customfield="Variant.Specs.Name"></customtextfield>
<customtextfield ng-maxlength="25" customfield="Variant.Specs.Title"></customtextfield>
Would you happen to know what I am doing wrong?
This piece of code should do it. Let's keep it as simple as possible. :)
HTML:
<div ng-app="autofocus">
<label>Name:</label>
<input ng-model="maxLengthReach"></input>
<br/><br/>
<label>Title:</label>
<input autofocus-when></input>
</div>
Javascript:
var app = angular.module('autofocus', []);
app.directive('autofocusWhen', function () {
return function (scope, element, attrs) {
scope.$watch('maxLengthReach', function(newValue){
if (newValue.length >= 5 ) {
element[0].focus();
}
});
}
});
jsFiddle: http://jsfiddle.net/gctvyfcz/1/
Your first error is your markup is wrong for using the directive. Should be
<input auto-tab-to="Variant.Specs.Title" ng-maxlength="4" customfield="Variant.Specs.Name"></input>
Directive should be changed to:
app.directive('autoTabTo', [function () {
return {
restrict: "A",
link: function (scope, el, attrs) {
el.bind('keyup', function(e) {
if (this.value.length === parseInt(attrs.ngMaxlength)) {
var element = document.getElementById(attrs.autoTabTo);
if (element)
element.focus();
}
});
}
}
}]);
Also, you don't have an ID on your second element so it won't find it:
<input ng-maxlength="4" customfield="Variant.Specs.Title" id="Variant.Specs.Title"></input>
working plunker
I do not want a user to enter spaces in a text field. I don't want it on submit validation but rather - a space will not show up on the text field when they click it.
The selected answer is arguably not very unobtrusive. And if you need to use it in multiple places, you'll end up with duplicated code.
I prefer to prevent the input of spaces using the following directive.
app.directive('disallowSpaces', function() {
return {
restrict: 'A',
link: function($scope, $element) {
$element.bind('input', function() {
$(this).val($(this).val().replace(/ /g, ''));
});
}
};
});
This directive can be invoked like this:
<input type="text" disallow-spaces>
<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text">
Update:
To improve code quality you can create custom directive instead. But don't forget that your directive should prevent input not only from keyboard, but also from pasting.
<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue">
Here is important to add ng-trim="false" attribute to disable trimming of an input.
angular
.module('app')
.directive('restrictField', function () {
return {
restrict: 'AE',
scope: {
restrictField: '='
},
link: function (scope) {
// this will match spaces, tabs, line feeds etc
// you can change this regex as you want
var regex = /\s/g;
scope.$watch('restrictField', function (newValue, oldValue) {
if (newValue != oldValue && regex.test(newValue)) {
scope.restrictField = newValue.replace(regex, '');
}
});
}
};
});
If you want to achieve it without writing directive
ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()"
THe directive Jason wrote did not work for me. I had to change return false to: e.preventDefault() like so:
app.directive('disallowSpaces', function() {
return {
restrict: 'A',
link: function($scope, $element) {
$element.bind('keydown', function(e) {
if (e.which === 32) {
e.preventDefault();
}
});
}
}
});
This works to prevent entering any special chars including spaces:
app.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == null)
return ''
let cleanInputValue = inputValue.replace(/[^\w]|_/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
Use without jquery
angular.module('app').directive('disallowSpaces', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
maxvalue: '=',
},
link: function ($scope, $element, attr, ngModelCtrl) {
$element.bind('keydown', function () {
function transformer(text) {
if (text) {
var transformedInput = text.replace(/ /g, '');
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(transformer);
});
},
};
});
// use disallow-spaces
<input type="text" ng-model="name" disallow-spaces />
You can achieve this without writing a directive.
<input ng-model="myModel" ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()">
For Angular 9 ,Keycode is not support.
Below code can help you for that.
keyDownHandler(event) {
if (event.code === 'Space') {
event.preventDefault();
}
}
I am looking for ways to limit the value inside the input to 4 and process the 4 digit value unto my controller.
<input type="number" class="form-control input-lg"
ng-model="search.main" placeholder="enter first 4 digits: 09XX">
{{ search.main | limitTo:4}}
Can always make a directive for it:
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on("keypress", function(e) {
if (this.value.length == limit) e.preventDefault();
});
}
}
}]);
<input limit-to="4" type="number" class="form-control input-lg" ng-model="search.main" placeholder="enter first 4 digits: 09XX">
You can always use ng-minlength, ng-maxlength for string length and min, max for number limits. Try this
<input type="number"
name="input"
class="form-control input-lg"
ng-model="search.main"
placeholder="enter first 4 digits: 09XX"
ng-minlength="1"
ng-maxlength="4"
min="1"
max="9999">
DEMO FIDDLE
No need to use an AngularJS directive.
Just use the good old standard html attribute maxlength.
<input type="text" maxlength="30" />
I used the accepted answer as a launching point, but this is what I came up with.
angular.module('beastTimerApp')
.directive('awLimitLength', function () {
return {
restrict: "A",
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
attrs.$set("ngTrim", "false");
var limitLength = parseInt(attrs.awLimitLength, 10);// console.log(attrs);
scope.$watch(attrs.ngModel, function(newValue) {
if(ngModel.$viewValue.length>limitLength){
ngModel.$setViewValue( ngModel.$viewValue.substring(0, limitLength ) );
ngModel.$render();
}
});
}
};
});
usage
<input name="name" type="text" ng-model="nameVar" aw-limit-length="10"/>
The key is to use $setViewValue() and $render() to set and display the changes respectively. This will make sure $viewValue and $modelValue are correct and displayed properly. You also want to set ngTrim to false to prevent the user adding whitespaces beyond the limit. This answer is an amalgamation of #tymeJV's answer and this blog post... https://justforchangesake.wordpress.com/2015/01/10/useful-angularjs-directives/
Will do it allowing backspaces and deletes.
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
angular.element(elem).on("keydown", function() {
if(event.keyCode > 47 && event.keyCode < 127) {
if (this.value.length == limit)
return false;
}
});
}
}
}]);
you can use this code:
<input type="number" class="form-control input-lg"
ng-model="search.main"
ng-keypress="limitKeypress($event,search.main,4)"
placeholder="enter first 4 digits: 09XX">
and AngularJS code:
$scope.limitKeypress = function ($event, value, maxLength) {
if (value != undefined && value.toString().length >= maxLength) {
$event.preventDefault();
}
}
We can use ng-value instead:
ng-value="(minutes > 60 ? minutes = 0 : minutes)"
In html code:
<input type="text" class="form-control" ng-model="minutes" ng-maxlength="2" ng-pattern="/^[0-9]*$/" ng-value="(minutes > 60 ? minutes = 0 : minutes)"/>
This will check for the value and if it is greater than 60, it replaces the value with 0.
As there is a problem in above directive (answer of tymeJV). If you enter maximum length once, then it will not accept any other character even the backspace. That is if limit-to="4" and if you entered 4 character in input box, then you will not able to delete it. SO here is the updated answer.
app.directive("limitTo", [function () {
return {
restrict: "A",
link: function (scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
elem.bind('keypress', function (e) {
// console.log(e.charCode)
if (elem[0].value.length >= limit) {
console.log(e.charCode)
e.preventDefault();
return false;
}
});
}
}
}]);
Angular material has a directive mdMaxlength, if you want to cut off the input at this length, you can use this directive:
app.directive("forceMaxlength", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.mdMaxlength);
angular.element(elem).on("keydown", function() {
if (this.value.length >= limit) {
this.value = this.value.substr(0,limit-1);
return false;
}
});
}
}
}]);
Usage:
<input type="text" md-maxlength="30" force-maxlength=""/>
We can write the directive to listen to the keypress event. But for some old browsers, this event is not triggered. Thats why i created a directive in such a way that there's no dependency on browser specific events limitation.
I created an angular directive to limit the number of text in the input box.
'use strict';
angular.module("appName")
.directive("limitTo", [function() {
return {
restrict: "A",
require: "ngModel",
link: function(scope, elem, attrs, ctrl) {
var limit = parseInt(attrs.limitTo);
ctrl.$parsers.push(function (value) {
if (value.length > limit){
value = value.substr(0, limit);
ctrl.$setViewValue(value);
ctrl.$render();
}
return value;
});
}
}}]);
Usage: <input limit-to="3" ng-model="test"/> would allow only 3 characters in input box.
In Angular Js Material we can limit input field by "maxLimit", for example we need limit of input text should b 60 character as:
maxLimit ='60'
complete code:
<form-input-field flex
class="input-style-1"
title="Quick response tag title"
placeholder="Write a catchy title to help users get more information on the service card"
form-name="parent.qrtForm"
show-error="showError"
name="title"
maxLength="65"
text-limit="65"
required="true"
ng-model="newQrt.tagName">
Run this operation on any change to the number:
var log = Math.log(number) / Math.log(10);
if (log >= 4)
number = Math.floor(number / Math.pow(10, Math.ceil(log - 4)));
This will always limit "number" to 4 digits.
I am reiterating what #Danilo Kobold said.
I had to make sure that users can enter only numbers (0-9) [Without 'e' or '.' or '-'] and a limit of 4 values only.
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
var exclude = /Backspace|Enter/;
angular.element(elem).on("keydown", function(e) {
if (event.keyCode > 47 && event.keyCode < 58) {
if (this.value.length == limit) e.preventDefault();
} else if (!exclude.test(event.key)) {
e.preventDefault();
}
});
}
}
}]);
If you want to use only limit then use
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
var exclude = /Backspace|Enter/;
angular.element(elem).on("keydown", function(e) {
if (!exclude.test(event.key)) {
if (this.value.length == limit) e.preventDefault();
}
});
}
}
}]);
You can add more keys if you want to the exclude variable, like this:
var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;
Got idea from this post
Hope I helped someone.
You can just use
ui-mask="9999"
as attribute in your view.
**
app.directive("limitTo", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
var exclude = /Backspace|Enter/;
angular.element(elem).on("keydown", function(e) {
if (e.keyCode > 47 && e.keyCode < 58) {
if (this.value.length == limit) e.preventDefault();
} else if (!exclude.test(e.key)) {
e.preventDefault();
}
});
}
}
}]);
**
Use this directive if you want to restrict max length for a input field which is present as part of custom directive template. This is the native html5 way of restricting max-lenth. This will also handle the copy paste case also to restrict till the maxlength on pasting.
app.directive('inputWrapper', function() {
return {
restrict: 'A',
template: "<input type='text'/>"
};
});
app.directive('maxInputLength', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.maxInputLength);
angular.element(elem).find('input').attr('maxlength', limit);
}
};
});
<input-wrapper max-input-lenth="35"></input-wrapper>
Do this instead
<input type="text" class="form-control input-lg" ng-model="search.main" placeholder="enter first 4 digits: 09XX" maxlength="4" num-only>{{ search.main | limitTo:4}}
use the type "text", then use maxlength to limit it and also use the num-only option to make it number input only
I am following an example based on official docs to validate float. My added requirement is that float value should lie between -90 to 90. I added the min and max fields but still no luck.
Below is the code:
HTML:
<body ng-app="form-example1">
<form name="form" class="css-form" novalidate>
<div>
Length (float):
<input type="text" ng-model="length" name="length" min="-90" max="90" smart-float />
{{length}}<br />
<span ng-show="form.length.$error.float">
This is not a valid float number!</span>
<span ng-show="form.length.$error.min || form.length.$error.max">
The value must be in range -90 to 90!</span>
</div>
JS:
var app = angular.module('form-example1', []);
var FLOAT_REGEXP = /^\-?\d+((\.|\,)\d+)?$/;
app.directive('smartFloat', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (FLOAT_REGEXP.test(viewValue)) {
ctrl.$setValidity('float', true);
return parseFloat(viewValue.replace(',', '.'));
} else {
ctrl.$setValidity('float', false);
return undefined;
}
});
}
};
});
Right now validations for min and max fields are not working. 90 is allowed but anything higher than is not allowed (like 90.12345 is not allowed, 90 is allowed, 89.9999 is allowed, -90.1 is not allowed)
Be sure to make your input of type number! The min/max validation is only available for this type of input field. Compare the docs for number to text.
<input type="text" name="number" smart-float>
app.directive('smartFloat', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9.]/g, '');
if (transformedInput !== inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});