gpt4 book ai didi

javascript - 如何通过验证将冒号自动放入 mac 地址的文本框中(javascript 或 angularjs)?

转载 作者:行者123 更新时间:2023-11-27 22:36:59 25 4
gpt4 key购买 nike

我需要在每两位数字后自动添加冒号(:)。所以它看起来像:DD:A4:55:FD:56:CC

我已经编写了一个逻辑,现在我也可以输入冒号,但是当我按退格键时,我无法从冒号返回。

当我将光标放在已经写入的两位数字上时,它允许写入超过两位数字,这是我不想要的。

这是我的代码:
HTML:

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

JS:

$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 + ':';
}
else{
console.log('no');
}
}

请知道我哪里错了。谢谢 !提前...

最佳答案

您可以使用正则表达式进行简化。我向您的输入添加了一个默认值,并添加了一个按钮,如果 macAddress 的长度有效,该按钮将调用这行代码:

macAddr.replace(/(.{2})/g,"$1:").slice(0,-1).toUpperCase();

代码:

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;
console.log("Tadaaa");
}
// 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>
</div>

关于javascript - 如何通过验证将冒号自动放入 mac 地址的文本框中(javascript 或 angularjs)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com