javascript 只允许在 html textinput 中输入某些字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16434174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:39:49  来源:igfitidea点击:

Only allow certain characters to be entered in html textinput

javascriptcharacterlimittextfield

提问by baburao113

I just need to allow a user to enter the following characters in the textinput:

我只需要允许用户在 textinput 中输入以下字符:

a-zA-Z0-9!@#$%^*_|

a-zA-Z0-9!@#$%^*_|

<form action="http://www.cknuckles.com/cgi/echo.cgi" method="get" name="logOn">
  User Name:<br />
  <input type="text" name="userName" size="25" /><br />
  Password:<br />
  <input type="password" name="pw" size="25" /><br />
  <input type="submit" value="Log In" onClick="validate()"/> 
</form>

Above is my HTML, and Below is my JavaScript I tried to use to validate it - but it doesnt work - any clues.

上面是我的 HTML,下面是我试图用来验证它的 JavaScript - 但它不起作用 - 任何线索。

<script language="javascript">
   document.logOn.onsubmit=validate;

   function validate(){

var name=document.logOn.pw.value;
    if(!name = "[a-zA-Z0-9!@#$%^*_|]"){              
alert("Your Password Cant Have any thing other than a-zA-Z0-9!@#$%^*_| - Play It Straight!");
    return false;
}               

    return true;
}

</script>

But This isnt working. I can still put chars in like ">" and "<" and "{" etc.

但这不起作用。我仍然可以将字符放入 ">" 和 "<" 和 "{" 等。

Any Thoughts?

有什么想法吗?

回答by Ankit Dhadse

You can try in your input text as below:

您可以尝试输入文本,如下所示:

<input type="text" pattern="[a-zA-Z0-9!@#$%^*_|]{6,25}" />

So the code changes look like below:

所以代码更改如下所示:

    <form action="#" method="get">
       User Name:<br />
       <input type="text" pattern="[a-zA-Z0-9!@#$%^*_|]{6,25}" /><br />
       Password:<br />
       <input type="password" /><br />
       <input type="submit" value="Log In" /> 
   </form>

this will do it without using JavaScript. patterncan be used instead.

这将在不使用 JavaScript 的情况下完成。pattern可以代替。

It is rather effective than JavaScript for form validation.

它在表单验证方面比 JavaScript 更有效。

回答by 5z- -

use this

用这个

<script language="javascript">
document.logOn.onsubmit=validate;

function validate(){

var name=document.logOn.pw.value;
var reg=/[^a-zA-Z0-9\!\@\#$\%\^\*\_\|]+/;
if(reg.test(name)){              
alert("Your Password Cant Have any thing other than a-zA-Z0-9!@#$%^*_| - Play It    Straight!");
return false;
}               

return true;
}

</script>

回答by AtanuCSE

This should do

这应该做

<input type="text" name="something" pattern="[a-zA-Z0-9!@#$%^*_|]{0,100}">

回答by Aniket Jha

Invalid Inputs

无效输入

Many times we want to make validations on an input box for characters that user can type. And other characters will not be entertained in the input box.

很多时候我们想对用户可以输入的字符的输入框进行验证。其他字符将不会在输入框中被娱乐。

Question: Make a input box that accepts digitsand spacesonly. Also, care for copy-paste (Ctrl +V ) of invalid characters.

问题:制作一个只接受数字空格的输入框。另外,请注意无效字符的复制粘贴(Ctrl +V)。

The first step is to register event on input tag. But what event type? We are typing characters into it so keypressevent looks fine.

第一步是在输入标签上注册事件。但是什么事件类型?我们正在向其中输入字符,因此keypress事件看起来不错。

<input type="text" id="input"/>
const input = document.getElementById('input');
var currentInputValue = '';
input.addEventListener('keypress', function inputKeypressHandler(e) {
    // keypress event on input box is listened here and this function is triggered
    // which key is pressed, keyPressed = e.which || e.keyCode; 
    const key = e.which || e.keyCode;
    // key code corresponds to digits 0-9 or space then okay
    // 0-9 key code is 48-57
    // space keycode is 32
    const SPACE = 32; // May be just stored somewhere
    const ZERO = 48;
    const NINE = 57;
    // valid digit is b/w 0-9 thus invalid will be lt 0 or gt 9
    const isNotValidDigit = key < ZERO || key > NINE;
    // if key is not a space or not a digit prevent this event
    if (key != SPACE || ( isNotValidDigit ) ) {
        e.preventDefault();
    }
});

This is pretty good solution but this doesn't prevent paste cheats. And that is because the keypressevent only records key pressed inside input box. A better event type is requried. inputit runs on all input ways including copy paste and drag.

这是一个很好的解决方案,但这并不能防止粘贴作弊。那是因为该keypress事件只记录输入框内按下的键。需要更好的事件类型。input它在所有输入方式上运行,包括复制粘贴和拖动。

var currentInputValue = '';
input.addEventListener('input', function inputInputEventHandler(e) {
    // use target of event to get value of input
    const target = e.target;
    // we can use regex to check if current input value
    // is valid input
    const DIGITS_SPACE_REGEX = /^[0-9\s]*$/;
    // test if target.value or value of input box now is valid.
    // if value is valid then update currentInputValue 
    // target.value else its is not value and we will
    // ignore this target.value and replace it with 
    // previously valid value currentInputValue
    DIGITS_SPACE_REGEX.test(target.value) 
        ? ( currentInputValue = target.value ) 
        : ( target.value = currentInputValue );
});

This solves our problem of paste but there is one problem here. Say you paste something Ctrl/Cmd + Vyour current cursor position will be lost and moved to starting. This must not haapen and you must be able to retain cursor position.

这解决了我们粘贴​​的问题,但这里有一个问题。假设您粘贴了一些Ctrl/Cmd + V当前光标位置将丢失并移动到开始位置的内容。这一定不能发生,您必须能够保留光标位置。

// Track cursor position
// cursor position is changed when you type something
const cursorState = {};
input.addEventListener('keydown', function inputKeydownHandler(e) {
    const target = e.target;
    // record the start and end
    cursorState.selectionStart = target.selectionStart;
    cursorState.selectionEnd = target.selectionEnd;
});

now in inputhandler

现在在input处理程序中

// modify
DIGITS_SPACE_REGEX.test(target.value) 
        ? ( currentInputValue = target.value ) 
        : ( target.value = currentInputValue );
 // to
 if (DIGITS_SPACE_REGEX.test(target.value)) {
     currentValue = target.value;
 }
 else {
    target.value = current.value;
    // restore cursor state
    target.setSelectionRange(
        cursorState.selectionStart,
        cursorState.selectionEnd
    );
 }

回答by FloatingCoder

Try this...

试试这个...

if(!/[a-zA-Z0-9!@#$%^*_|]./.test(name)){    

回答by kundan

Try this and revert me back if it works for you

试试这个,如果它对你有用,就让我回来

function validate(){
        var name=document.logOn.pw.value;
        var test = new RegExp("[a-zA-Z0-9!@#$%^*_|]");
        if(!name.match(test)){              
           alert("Your Password Cant Have any thing other than a-zA-Z0-9!@#$%^*_| - Play It                     Straight!");
        return false;
  }               
   return true;
}

http://jsfiddle.net/KJEcG/

http://jsfiddle.net/KJEcG/