PiyaModi PiyaModi - 2 months ago 14x
AngularJS Question

How to put colon automatically in text box for mac address with validation (javascript or angularjs)?

I need to put colon (:) automatically after every two digit.
So it will look like: DD:A4:55:FD:56:CC

I have write a logic and now I am able to put colon as well, but when I am pressing backspace I am not able to go back from colon.

And it is allowing to write more than two digit when i put cursor on already written two digit, which I don't want.

Here is my code:


<input type="text" ng-model="mac.macAddress" name="macAddress" id="macAddress"
maxlength="17" ng-change="macAddressFormat(mac)">


$scope.macAddressFormat = function(mac){

var macAddress = mac.macAddress;

var filteredMac = macAddress.replace(/\:/g, '');
var length = filteredMac.length;

if(length % 2 == 0 && length > 1 && length < 12){
mac.macAddress = mac.macAddress + ':';

Please, know me where I am wrong.
Thanks ! in advance...


You can simplify using Regex. I added a default value to your input and added a button which will call this line of code if the length of the macAddress is valid:


The Code:

var app = angular.module("macformat", []); 
app.controller("myCtrl", function($scope) {
  $scope.macAddressFormat = function(mac){

    mac.macAddress = mac.macAddress.toUpperCase();
    var macAddr  = mac.macAddress;
    var alphaNum= /^[A-Za-z0-9]+$/;

    // The Input will be changed only if the length is 12 and is alphanumeric
    if(macAddr.length == 12 && alphaNum.test(macAddr)){
        // A lot is going on here. 
        // .replace(/(.{2})/g,"$1:") - adds ':' every other 2 characters
        // .slice(0,-1) - cuts the last character, because ':' is added
        // .toUpperCase() - because it's good practice for writing MAC Addresses
        macAddr = macAddr.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();
        // Place Formatted MAC Address to Input
        mac.macAddress = macAddr;
    // Developer info in console if length is not 12
    else if (macAddr.length < 12 && alphaNum.test(macAddr)){
        console.log(12 - macAddr.length + " characters left");
    else if (macAddr.length > 12 && alphaNum.test(macAddr)){
        console.log(macAddr.length - 12 + " characters too many");
    // Developer info in console if macAddress contains non alpha-numeric
    else if (!alphaNum.test(macAddr)){
        console.log("only alpha-numeric allowed");
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="macformat" ng-controller="myCtrl">
  <p>Write MAC Address here without ":" and it will be formatted automatically:</p>
  <input type="text" ng-model="mac.macAddress" name="macAddress" id="macAddress" 
           maxlength="17" ng-change="macAddressFormat(mac)">
  <p><i>Check console for info</i></p>