I have these inputs inside a form which I'm validating with angular's ng-pattern
, ng-required
and ng-model
directives:
<div class="form-group">
<div style="padding-left:0px;" ng-class="{'has-error':personalDataForm.phone.$invalid && personalDataForm.phone.$dirty}" class="col-md-6">
<label>Teléfono</label>
<input type="text" name="phone" ng-pattern="/[0-9]{3}-[0-9]{7}/" ng-required="true" ng-trim="true" ng-model="phone" class="form-control phoneRegexInput"/>
</div>
<div style="padding-left:0px;" ng-class="{'has-error':personalDataForm.mobile.$invalid && personalDataForm.mobile.$dirty}" class="col-md-6">
<label>Celular</label>
<input type="text" name="mobile" ng-pattern="/[0-9]{3}-[0-9]{7}/" ng-required="true" ng-trim="true" ng-model="mobile" class="form-control phoneRegexInput"/>
</div>
</div>
So the ng-pattern
directive will look for strings in the format of 7 digits prefixed by 3 digits and a hyphen, for example: 287-8719423.
As I don't want to force user to input the hyphen sign, I got a jQuery function which will put that hyphen when the input has completed the 3 required digits, this is my function:
$(".phoneRegexInput").keyup(function() {
var phone = $(this).val();
console.log(phone + " didnt match");
if (phone.match(/\d{10}/)) {
phone = phone.substr(0, 3) + "" + '-' + phone.substr(3);
console.log(phone);
$(this).val(phone);
}
});
It's working properly and it actually changes the input value to a correctly formated one but it won't validate it as correct. If I delete and type again a correct input it will.
So I think is is caused because validation is fired from an actual user input, how can I make it listen from any change?
Related question.
I know this might be related to this question, but the problem is that the model
won't change neither as it's not valid.
How should I fix it?
Workaround
I thought, "change the model", so I tried:
$(".phoneRegexInput").keyup(function() {
var phone = $(this).val();
console.log(phone + " didnt match");
if (phone.match(/\d{10}/)) {
phone = phone.substr(0, 3) + "" + '-' + phone.substr(3);
console.log(phone);
// Attempt to change model
if ($scope.personalData)
$scope.personalData.phone = phone;
else {
$scope.personalData = {
phone: phone
}
}
console.log($scope.personalData);
}
});
But now something even more strange happens, I can see an actual object as $scope.personalData
when loggin but if I try to debug by {{personalData}} at markup, it won't seem to have the property.
Nevermind, I have to make the validation background watch or listen to changes at the model.