After encountering issues with Ian Haggerty's answer form code, I had to make some modifications and additions. The code initially worked fine, but when I started testing it in various ways, problems arose. Specifically, I was attempting to test for values less than 100, which resulted in unexpected outcomes.
One particular issue was that if I inputted 100 and then tried to add a decimal point to make it 10.0, the code did not recognize this as valid based on my regex (despite allowing up to two decimals). It seemed to always tack on the new character at the end of the string being evaluated, even when I inserted it in the middle.
To address this discrepancy, I implemented a change where the original value is saved on "keypress," and then on "keyup" (or alternatively, "change"), the new value is checked against the regex. If deemed invalid, it reverts back to the original value.
Although this method briefly updates the model, it allows for inserting characters in the middle or beginning of the input field while still ensuring accurate regex matching. For Angular 1.3, utilizing ng-model-options="{debounce:250}" may help mitigate this issue. Keeping any code reliant on model changes idempotent proves to be incredibly beneficial.
usage: <input ... validate-with="/^([\d]{1,2}\.[\d]{1,2}|\.?[\d]{1,2}|100)?$/" />
.directive("validateWith", [function(){
return {
restrict: "A",
link: function($scope, $el, $attrs){
var regexp = eval($attrs.validateWith);
var origVal;
// saving the current value before any changes are made
$el.on("keypress", function(e){
origVal = $el.val();
});
// validating the new value after changes are made
// reverting to the original value if invalid
$el.on("keyup", function(e){
if(!regexp.test($el.val())){
$el.val(origVal);
}
});
}
}
}]);