var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
/*
maxlines attribute directive, specify on a <textarea> to validate the number
of lines entered is less than the specified value.
Optional attributes:
maxlines-prevent-enter: Specify as false to NOT block the pressing of the Enter
key once the max number of lines has been reached.
*/
app.directive('maxlines', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
var maxLines = 1;
attrs.$observe('maxlines', function(val) {
maxLines = parseInt(val);
});
ngModel.$validators.maxlines = function(modelValue, viewValue) {
var numLines = (modelValue || '').split("\n").length;
return numLines <= maxLines;
};
attrs.$observe('maxlinesPreventEnter', function(preventEnter) {
// if attribute value starts with 'f', treat as false. Everything else is true
preventEnter = (preventEnter || '').toLocaleLowerCase().indexOf('f') !== 0;
if (preventEnter) {
addKeypress();
} else {
removeKeypress();
}
});
function addKeypress() {
elem.on('keypress', function(event) {
// test if adding a newline would cause the validator to fail
if (event.keyCode == 13 && !ngModel.$validators.maxlines(ngModel.$modelValue + '\n', ngModel.$viewValue + '\n')) {
event.preventDefault();
}
});
}
function removeKeypress() {
elem.off('.maxlines');
}
scope.$on('$destroy', removeKeypress);
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="//code.angularjs.org/1.3.0/angular.js" data-semver="1.3.0"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Try to type more than 5 lines in this textarea:</p>
<textarea ng-model="dummy.value" rows="10" cols="30" maxlines="5" maxlines-prevent-enter="true"></textarea>
</body>
</html>
/* Put your css in here */
.ng-invalid-maxlines {
outline: 5px solid red;
}