I have a form which I'm in the process of changing my phone fields from using a regex to the intl-tel-input module. I'm running into problems & confusion in checking for valid #s.
I have a form with several of these fields...
<div class="row">
<div class="col-xs-2">
<label for="cellPhone"
translate>CONTACT.CELL</label>
</div>
<div class="col-xs-6"
ng-class="{'has-error': !cellPhoneFocus && forms.contactForm.cellPhone.$invalid && forms.contactForm.cellPhone.$touched }">
<input type="text" class="form-control intlPhoneInput"
id="cellPhone" name="cellPhone"
ng-model="contact.cellPhone.display"
ng-focus="cellPhoneFocus = true"
ng-blur="cellPhoneFocus = false; validatePhone($event)">
<div ng-messages="forms.contactForm.cellPhone.$error"
ng-show="!cellPhoneFocus && forms.contactForm.cellPhone.$touched"
class="errorMessages">
<p ng-message="pattern" translate>
CRUD.VALID_PHONE</p>
</div>
</div>
and the submit...
<button type="submit" class="btn btn-primary" ng-disabled="forms.contactForm.$invalid" id="saveContactLink" translate>CRUD.SAVE</button>
Then in my controller (Typescript)...
//In Constructor
$scope.validatePhone = this.validatePhone.bind(this);
//Outside constructor
private validatePhone(eventObject: any) {
let thePhoneField = $('#' + eventObject.target.id);
let phoneIsValid = thePhoneField.intlTelInput("isValidNumber");
this.$scope.forms.contactForm[eventObject.target.id].$invalid = !phoneIsValid;
this.$scope.forms.contactForm[eventObject.target.id].$error = {"pattern": !phoneIsValid};
}
This properly sets my has-error class and error message, but it doesn't set the FORM to invalid. I've tried $setValidity...
this.$scope.forms.contactForm[eventObject.target.id].$setValidity('pattern', !phoneIsValid);
...but it doesn't seem to do anything at all.
How do I set the field to invalid, show the correct ng-message(if there's more than one), and make sure the form $errors gets updated so the submit is disabled?
Turns out $setValidity WAS working, but having setValidity along with .$invalid and $error caused some crossed wires. Commenting out the last two enabled/disabled my submit button correctly when invalidating a field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With