Restrict Special Characters in HTML & AngularJs - html

` ~ ! # # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . /
I want to restrict the above mentioned special characters and numbers in the input text field. I used the
ng-pattern="/^[a-zA-Z ]*$/"
to restrict the special characters. This pattern is blocking all the special characters. I am facing issue when I want to enter name "PĂ©rez Gil" I don't want to restrict other language text.

Updates:
I think $parsers is the best options here. See the updated code and plunker.
Controller
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
}])
.directive('myDirective', function() {
function link(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
var reg = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
// if view values matches regexp, update model value
if (viewValue.match(reg)) {
return viewValue;
}
// keep the model value as it is
var transformedValue = ngModel.$modelValue;
ngModel.$setViewValue(transformedValue);
ngModel.$render();
return transformedValue;
});
}
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
Template
<input type="text" ng-model="model" id="input" name="input" my-directive />
Here's a updated example on Plunker
https://plnkr.co/edit/eEOJLi?p=preview
Old Answers:
Since you already have a list of characters that you want to restrict, you can spell them out in the ng-pattern expression like:
Controller
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
}]);
Template
<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" />
Here's a working example on Plunker
https://plnkr.co/edit/eEOJLi?p=preview

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
};
});
In Html:
<input type="text" ng-model="coupon.code" restrict-Special-Characters-Directive>

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" ng-change="Check(myValue)" ng-model="myValue" />
<p ng-show="test">The Special Character not accept.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope,ngModel) {
$scope.Check= function(x) {
var reg = /^[^`~!##$%\^&*()_+={}|[\]\\:';"<>?,./]*$/;
if (!x.match(reg)) {
$scope.myValue = x.substring(0, x.length-1);
$scope.test=true;
}
else
{
$scope.test=false;
}
};
}]);
</script>
</body>
</html>

Related

Can I pass a string in angularJs directive template?

I am new to angularJS. Here is my sample code :
app.directive("w3TestDirective", function() {
return {
template : '<ul>'+
'<div ng-repeat="rows in roleMenulistByID">'+
'<li>{{rows.route_alias_name}}</li>'+
'</div>'+
'</ul>'
};
});
My question is can I send the template data as an angular string? Say,
$scope.string = '<ul>'+
'<div ng-repeat="rows in roleMenulistByID">'+
'<li>{{rows.route_alias_name}}</li>'+
'</div>'+
'</ul>';
how can I achieve that? if I say
template : $scope.string
It shows an error. Please help & thanks in advance.
You can pass template string via corresponding attribute and use function at directive declaration as value of template property:
angular.module('app', []).directive('test', function() {
return {
restrict: 'E',
replace: true,
template: function(el, attrs) {
return attrs.template;
}
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-init='items=[1,2,3]'>
<test template='<p ng-repeat="x in items">{{x}}</p>'><test>
</div>

why $scope.logo is undefined in controller ?

This is my HTML form
<form ng-submit='create()'>
..
.
.
<input type='file' ng-model='logo' accept="image/*">
</form>
this is my controller :
$scope.create = function () {
$scope.Ent = {}
$scope.Ent.logo = $scope.logo;
ng-model won't work in input type 'file. use a custom directive to bind it
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread = loadEvent.target.result;
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}]);
assign scope variable to fileread attribute
<form ng-submit='create()'>
..
.
.
<input type='file' fileread='logo' accept="image/*">
</form>

Directive not working for input type=number using angularjs

I have a input type= number field.It allows whole number and decimal number.But I need only whole number to be enter in the input.I have created a directive which is working only for input type=text,not working for input type=number.The reason is I need a number keyboard in mobile.
Below code is for number only,
Angularjs :
.directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9-]/g, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return '';
}
ngModelCtrl.$parsers.push(fromUser);
}
};
})
Html:
<input type="number" ng-model="points" numbers-only required>
Any suggestions welcome
Try this
html
<input type="text" ng-model="myText" name="inputName" numbers-only>
directive
myApp.directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'').replace('.','') : null;
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
https://jsfiddle.net/vorant/Lzw0yoma/

"[object object]" shown when double-clicking input

Below is the template I am using for the directive. In code we are
fetching the data from a service in that data we have all the
information of that particular person. And from that data we are
showing only first name, last name and designtion or company
affiliation.
<div ng-if="model" class="entry-added">
<span class="form-control"><b>{{model.fullName}}</b>, <br/><span class="small-font">{{(model.designation)?model.designation:model.companyAffiliation}}</span></span>
<a ng-click="removePerson()" class="action-remove"><i class="fa fa-remove"></i></a>
</div>
<div ng-show="!model" class="input-group">
<input type="text"
class="form-control"
name="{{name}}"
id="{{name}}"
placeholder="{{placeholder}}"
ng-required="{{isRequired}}"
typeahead-on-select = "change($item, $model, $label)"
ng-model="model"
typeahead-min-length="3",
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
typeahead-template-url="typeAheadTemplate.html"
typeahead-loading="searching"
typeahead-editable="false">
<script type="text/ng-template" id="typeAheadTemplate.html">
<a class="ui-corner-all dropdown" tabindex="-1">
<div class="col-md-2"><img class="dropdown-image" ng-src="https://people.***.com/Photos?empno={{match.model.employeeNumber}}"></div>
<div>
<div bind-html-unsafe="match.model.fullName"></div>
<div bind-html-unsafe="match.model.designation"></div>
</div>
</a>
</script>
I am using a custom directive to display a search field. The drop down is displaying [object object].
Directive
// In backend taxDeptContact is a Person type object
/*
Directive code
*/
(function () {
'use strict';
angular.module('treasuryApp.directives').directive('employeeSearch', employeeSearch);
employeeSearch.$inject = ['$resource', '$rootScope', 'ErrorHandler'];
function employeeSearch($resource, $rootScope, ErrorHandler) {
return {
restrict: 'E',
require: '^form',
scope: {
model: "=",
isRequired: '#',
submitted: "=",
onSelect: '&',
name: '#',
index:'#'
},
link: function(scope, el, attrs, formCtrl) {
//set required attribute for dynamically changing validations
scope.searchEmployees = function (searchTerm) {
var users = [];
var myResult = [];
var result = $resource($rootScope.REST_URL + "/user/getEmployees", {term: searchTerm}).query().$promise.then(function (value) {
//console.log(value)
$.each(value, function(i, o) {
users.push(o);
});
return users;
});
return result;
}
scope.removePerson = function() {
scope.model=null;
}
scope.userNotSelectedFromTypeahead = function(name) {
if(undefined === formCtrl[name]) {
return false;
}
return formCtrl[name].$error.editable;
};
scope.change = function(item, model, label) {
scope.model = item
scope.onSelect(
{name: scope.name, person: scope.model});
},
templateUrl: 'app/components/common/directives/employee-search.tpl.html'
};
}
})();
View that is using the directive
<div class="form-group">
<label class="col-sm-3>Tax Dept Contact</label>
<div class="col-sm-4">
<employee-search model="reqCtrl.requestObj.taxDepartmentContact" name="taxDeptContact" is-required="false" submitted="reqCtrl.submitted"/>
</div>
</div>
Image of the error occuring
Looks like this may be your trouble spot
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
suggestion for suggestion is pulling the whole object. Have you tried displaying a particular attribute of suggestion?
For example: if you had a suggestion.name attribute you would write:
typeahead="suggestion.name for suggestion in searchEmployees($viewValue)"
Finally got the answer: I used autocomplete="off" in my directive and thats all
<input type="text" autocomplete="off" />

AngularJS $resource JSON field name conversion

I'm working on an AngularJS project that uses an API to deal with data. Now I'm implementing the 'create' functionality using $resource. Everything was going well except the naming conversion: I use camelCase but the API accepts snake_case only.
Is there a way to automatically convert these keys to snake_case?
Service:
services.factory('Salons', ['$resource',
function ($resource) {
return $resource('/salons/:slug', {
slug: "#slug"
});
}
]);
Controller:
controllers.controller('CreateSalonController', ['$scope', 'Salons',
function ($scope, Salons) {
$scope.submit = function() {
Salons.save(this.salon);
};
}
]);
View:
<form name="salonForm" role="form" ng-submit="submit()">
<div class="form-group">
<label for="salonContactFirstName">First name</label>
<input name="contactFirstName" type="text" class="form-control" id="salonContactFirstName" data-ng-model="salon.contactFirstName" />
</div>
...
I have not found any built-in solution so I implemented one:
A new service:
services.factory('Util', function () {
var Util = {
stringToSnakeCase: function (input) {
return input.replace(/([0-9A-Z])/g, function ($1) {
return "_" + $1.toLowerCase();
});
},
objectKeysToSnakeCase: function (input) {
var output = {};
_.each(input, function (val, key) {
output[Util.stringToSnakeCase(key)]
= _.isObject(val) ? Util.objectToSnakeCase(val) : val;
});
return output;
}
};
return Util;
}
);
And the updated controller:
controllers.controller('CreateSalonController', ['$scope', 'Salons', 'Util',
function ($scope, Salons, Util) {
$scope.submit = function() {
Salons.save(Util.objectKeysToSnakeCase(this.salon));
};
}
]);