2017-04-01 123 views
0

我想限制输入到只有一个字符(R)和6位数字仅... 例如6位:R123896限制一个输入到仅特定的字符和数字

如果输入长度的增加7它将除去数字,如果第一个字是不是R,它应该替换字符“R”

我写了这个剧本,但不知道如何前进,它的形状是什么,我想...

$("#consultationident").keyup(function(key){ 
var txtVal = $(this).val(); 
if(isNumber(txtVal) && txtVal.length>6) 
{ 
    $(this).val(txtVal.substring(0,6)) 
} 
}); 

请帮忙!

回答

0

的使用regular expression的将是一个想法...

$("#consultationident").keyup(function(key){ 
 
    
 
    // Uppercase the first character. 
 
    var firstChar = $(this).val().substr(0,1).toUpperCase(); 
 
    var rest = $(this).val().substr(1); 
 
    
 
    $(this).val(firstChar + rest); 
 
    
 
    var txtVal = $(this).val(); 
 
    var pattern = /^(R)(\d{6})$/; 
 

 
    // Check if the value entered fits the pattern. 
 
    if(pattern.test(txtVal)){ 
 
    console.log("Value ok"); 
 
    }else{ 
 
    console.log("Value wrong"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input id="consultationident">

0

这里是使用正则表达式验证输入的代码

$("#consultationident").keyup(function(key){ 
    var txtVal = $(this).val(); 
    if(txtVal.length>6) 
    { 
     str = $(this).val().substring(0,7); 

     pattern = /^[a-zA-Z]{1}(\d{6})$/ 



     if(pattern.test(str)) { 
     str = str.replace(/^[a-zA-Z]/,"R") // Replace any character with "R" 
     console.log(str); 
    } 
     else { 
     console.log("invalid input"); 
     } 
    } 
});