简体   繁体   English

如何验证输入文本允许第一和第二位数字仅为字母

[英]How to verify that the input text allows the first and second digits to be only letters

I need to validate a input text, the first 2 digits only letters after adding a hyphen and finally 5 numerical digits.我需要验证输入文本,添加连字符后的前 2 位仅是字母,最后是 5 位数字。

format example: aa-12345格式示例:aa-12345

now i have我现在有

<asp:TextBox ID="txtCodigoTopografo" onkeydown="test(this)"   runat="server"></asp:TextBox>

function test(e) {
        console.log(e);

        switch (e.value.length) {

            case 0:
                if (e.value)
                e.value = e.value.replace(/[^a-z]/gi, '');
                break;

            case 1:
                e.value = e.value.replace(/[^a-z]/gi, ''); 
                break;
            case 2:
               e.value = e.value.replace(/[^0-9]/gi, '');
                break;
            case 3:
                e.value = e.value.replace(/[^0-9]/gi, '');
              
                break;
        }


       
        
       
    }

Your current method is trying to replace stuff with regex.您当前的方法是尝试用正则表达式替换东西。 Instead, use regex to verify your input string is in the correct format.相反,使用正则表达式来验证您的输入字符串的格式是否正确。

This regex assumes the letters must be lower case.此正则表达式假定字母必须为小写。 You can change [az] to [Az] if you allow upper or lower case.如果允许大写或小写,您可以将[az]更改为[Az]

 function test() { var textboxContent = document.getElementById("input").value; var passed = /^[az]{2}-\\d{5}$/.test(textboxContent); if (passed) { document.getElementById("result").textContent = "Passed!"; } else { document.getElementById("result").textContent = "Failed!"; } }
 <input type="text" id="input" placeholder="Type here!" oninput="test()" /> <p id="result"></p>

An explanation of the regex:正则表达式的解释:

^     Match the start of the input. Used so that you don't match part way along the input
[a-z] Match a lowercase letter...
{2}   ...2 times (you could do "[a-z][a-z]" instead)
-     Match hyphen
\d    Match a digit...
{5}   ...5 times (you could do "\d\d\d\d\d" instead)
$     Match the end of the input. Used so that you don't match part way along the input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM