如何使用正则表达式和JavaScript强制用户在输入字段中输入特定模式 [英] How do I force user to enter specific pattern in input field using regex and javascript
问题描述
我承认,尽管知道正则表达式的强大功能,但我从未对其进行过探索.并让我回味无穷. 我试图让用户在输入文本中输入模式P99999999,其中P是必需的,而99999999可以采用任何数字(不是字母).我正在触发键入,输入字段通过样式进行了大写,到目前为止,这是我所做的(我知道太少了).
I admit, I never explored into the regex albeit knowing its power. And its striking back to me. I am trying to make user enter pattern P99999999 into an input text where P is mandatory while 99999999 can take any digits(not letters). I'm triggering keyup, input field has uppercasing through styling and so far, this is what I have done (I know its too little).
inpt.value = $.trim( inpt.value );
if( inpt.value.indexOf( 'P' ) != 0 )
inpt.value = inpt.value.replace(/[A-Z]/g, '');
经过一番探索,我想出了这个
After some exploring I come up with this
[P]+[0-9]+(?:\.[0-9]*)?
我不知道该如何验证我的输入.这是由在线工具生成的.我知道这不应该那么难.任何帮助.
I do not know how to validate my input against this. This was generated by an online tool. I know it shouldn't be that hard. Any help.
推荐答案
[已更新,以解决流输入(按住键)问题]
您去哪里
regex [它可能看起来像是非常规的,因为可能没有(*)数字,但是再想一想,它是实时验证,而不是最终结果验证]:
regex [ it might look unconventional as there can be none (*) digits but think again, it is a live validation not the final result validation ]:
^P\d*$
代码:
$('input').on('change keyup keydown',function(){
var txt = $(this).val();
$(this).val(/^P\d*$/.test(txt)&txt.length<10?txt:txt.substring(0,txt.length-1));
});
这篇关于如何使用正则表达式和JavaScript强制用户在输入字段中输入特定模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!