简体   繁体   中英

How to restrict value for Input field?

I have Input filed - But it Should Accept only following string

A,C,D,K,1,2,3 and 5

If any other value is put it should not accept.

How Can I handle this?

使用正则表达式 .on onChange 文本输入道具,您只需使用正则表达式验证数据。

May be on the keypress event:

 //A,C,D,K,1,2,3 and 5 var allowedKeyCodes = [65,67,68,75,49,50,51,53] function validate(){ return allowedKeyCodes.includes(event.keyCode); }
 <input type="text" onkeypress="return validate()" >

 <HTML> <BODY> <input id="inputField" value="" onkeypress="validateInput(event)"/> </BODY> <script type="text/javascript"> function validateInput(e) { debugger; let userinput =String.fromCharCode(e.which); let regularExpression = new RegExp(/[ACDK1235]/); let isGoodInput = regularExpression.test(userinput); if(!isGoodInput){ alert('User typed bad input[ ' +userinput + ' ], so I am blocking input!'); e.preventDefault(); } else{ alert('User typed good input[ '+userinput+' ]'); } } </script> </HTML>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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