Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<div ng-app="myApp">
<form name="myForm">
<div ng-controller="MyCtrl">
<br>
<label>Input #1</label>
<br>
<input ng-model="formData.name" name='myName' my-custom-length="8" /> <span ng-show="myForm.myName.$error.maxlength">Max length exceeded by {{ myForm.myName.maxlength }}</span>
<br>
<br>
<label>Input #2</label>
<br>
<input ng-model="field.myEmail" name='myEmail' my-custom-length="3" /> <span ng-show="myForm.myEmail.$error.maxlength">Max length exceeded by {{ myForm.myEmail.maxlength }}</span>
<button ng-click="sendPost(formData)">dasdasddads</button>
<br>
</div>
</form>
</div>
CSS
input.ng-invalid {
border: 3px solid red !important;
}
JavaScript
var app = angular.module('myApp', []);
app.controller('MyCtrl', function ($scope) {
$scope.field = {};
});
app.directive("myCustomLength", function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
if (!ctrl) {
return
} // ignore if no ngModel controller
ctrl.$formatters.push(validateInput);
ctrl.$parsers.unshift(validateInput);
function validateInput(value) {
if (!value) {
updateValidity(false);
return
}
inputLength(value);
var state = value.length > attrs.myCustomLength;
updateValidity(state);
}
function inputLength(value) {
ctrl.maxlength = null;
var length = value.length > attrs.myCustomLength;
if (length) {
ctrl.maxlength = (value.length - attrs.myCustomLength).toString();
}
}
function updateValidity(state) {
ctrl.$setValidity('maxlength', !state);
}
} // end link
} // end return
});