2017-05-16 31 views
0

我有輸入框用戶輸入動態設置NG-圖案鹼

<input type="text" class="text-primary" ng-pattern="ip_regex or ipv6_regex" name="newIP" ng-model="macbinding.newIP" ng-change="checkDuplicates('newIP')"> 

我已經2種型態爲IPv4和IPv6準備。

$scope.ip_regex = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'; 


$scope.ipv6_regex = '((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?'; 

但我怎麼能動態地應用這些NG-模式的變化是輸入基地,如果一個字符串包含:

Ex。 2001::1

如果輸入包含:然後,我知道它的IPv6的話,我會用ng-pattern="ipv6_regex"

這東西,我可以在前端HTML實現,或者我需要解析輸入和做我角度控制器中的邏輯?

我可以使用ng-if嗎?

+0

的可能的複製[Angularjs動態ng模式驗證](http://stackoverflow.com/questions/18900308/angularjs-dynamic-ng-pattern-validation) – d9ngle

回答

1

您可以使用ng-model的組合來存儲和檢查用戶的輸入,以及timeOut函數來告訴您何時檢查輸入。例如。

您輸入的標籤是這樣的

<input id="textBox" ng-model="$ctrl.userInput" value="$ctrl.userInput"/> 

而且JS(我寫它的打字稿,但它應該是足夠的可閱讀,你得到的要點。)

userInput: string = ''; 

//setup before functions 
typingTimer: number; //timer identifier 

//on keyup, start the countdown 
$('#textBox').on('keyup', function() { 
    if (typingTimer){ 
     clearTimeout(typingTimer); 
    } 

    //if no keyup event is found in 3000ms (3 seconds) execute doneTyping() 
    typingTimer = setTimeout(doneTyping, 3000); 
}); 

//user is "finished typing," do something 
function doneTyping() { 
    //check for ':' 
    var foundSemiColon: boolean = false; 
    //for every character in, userInput see if that character's code value equals 58. 
    //58 is the ASCII representation of a semi-colon 
    for (var i: number = 0; i < userInput.length; i++) { 
     if (userInput.charCodeAt(i) === 58) { 
      //Semi-colon found use IPv6 
      break; 
     } 
    } 

    //if foundSemiColon === false you didn't find a semi-colon 
    if (!foundSemiColon) { 
     //use IPv4 
    } 

    //Now that you're done and know what to use, clear your timeOut event 
    clearTimeout(typingTimer); 
}