JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
Mobile Phone: <input type="text" ng-model="mobilephone" phoneformat name="mobilephone" />
<span class="error"
ng-show="myForm.mobilephone.$error.telephone">Numbers only!</span>
<span class="error"
ng-show="myForm.mobilephone.$error.telephone">Exact 10 Numbers only!</span>
<br />
Home Phone: <input type="text" ng-model="homephone" phoneformat name="homephone" />
<span class="error"
ng-show="myForm.homephone.$error.telephone">Numbers only!</span>
<span class="error"
ng-show="myForm.homephone.$error.telephone">Exact 10 Numbers only!</span>
<br />
Zip: <input type="text" ng-model="zip" zip-validation name="zip" />
<span class="error" ng-show="myForm.zip.$error.zip">Zip must contain 5 numbers</span>
</form>
</div>
JavaScript
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.mobilephone = "1234567890";
$scope.homephone = "5555551234";
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attr, ngModelCtrl) {
var phoneParse = function (value) {
var numbers = value && value.replace(/-/g, "");
if (/^\d{10}$/.test(numbers)) {
return numbers;
}
return undefined;
}
var phoneFormat = function (value) {
var numbers = value && value.replace(/-/g,"");
var matches = numbers && numbers.match(/^(\d{3})(\d{3})(\d{4})$/);
if (matches) {
return matches[1] + "-" + matches[2] + "-" + matches[3];
}
return undefined;
}
ngModelCtrl.$parsers.push(phoneParse);
ngModelCtrl.$formatters.push(phoneFormat);
element.bind("blur", function () {
var value = phoneFormat(element.val());
var isValid = !!value;
if (isValid) {
ngModelCtrl.$setViewValue(value);
ngModelCtrl.$render();
}
ngModelCtrl.$setValidity("telephone", isValid);
scope.$apply();
});
}
};
});
myApp.directive("zipValidation", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attr, ngModelCtrl) {
var zipVal = function (value) {
if (/^\d{5}$/.test(value)) {
return value;
}
return undefined;
}
...