I have the below phone number validation which automatically picks up brackets based on the condition.
I have an issue here, after giving the 10 digit phone number when we try to select the whole number and start typing on top of it, length of the value remains same (14) and brackets are not picking up and condition goes wrong.
Length should be cleared in this case.
Where am I missing?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.validatePhoneNumber = function(e){
var key = e.charCode || e.keyCode || 0;
// var regex = /^[0-9.\-\(\)]*$/;
var text = $('#phoneNumber');
console.log(text.val());
if ((e.which < 48 || e.which > 57)) {
e.preventDefault();
} else if (key !== 8 && key !== 9) {
if ((text.val().length === 0) && (!e.ctrlKey)) {
text.val(text.val() + '(');
}
if (text.val().length === 4) {
text.val(text.val() + ') ');
}
if (text.val().length === 9) {
text.val(text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" class="input-sm form-control" id="phoneNumber"
ng-model="search.phonenumber" placeholder="Phone Number"
ng-keypress="validatePhoneNumber($event)"
ng-paste="$event.preventDefault();"
ng-init="paste=false" maxlength="14">
</div>