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

时间:2013-05-08 06:35:59

标签: javascript character limit textfield

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

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>

上面是我的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>

但这不起作用。我仍然可以把字符放在“&gt;”中和“&lt;”和“{”等。

有什么想法吗?

6 个答案:

答案 0 :(得分:35)

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

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

所以代码更改如下所示:

    <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>

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

它比JavaScript更有效地进行表单验证。

答案 1 :(得分:3)

使用此

<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>

答案 2 :(得分:1)

这应该

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

答案 3 :(得分:0)

试试这个,如果适合你,请将其还原回来

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/

答案 4 :(得分:0)

试试这个......

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

答案 5 :(得分:0)

无效输入

很多时候,我们希望在输入框中对用户可以键入的字符进行验证。其他字符将不会在输入框中被接受。

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

第一步是在输入标签上注册事件。但是什么事件类型? ?我们正在输入字符,因此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();
    }
});

这是一个很好的解决方案,但这不能防止粘贴作弊。这是因为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 );
});

这解决了我们的粘贴问题,但是这里有一个问题。假设您粘贴一些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;
});

现在在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
    );
 }
相关问题