只允许在html textinput中输入某些字符 [英] Only allow certain characters to be entered in html textinput

查看:162
本文介绍了只允许在html textinput中输入某些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just need to allow a user to enter the following characters in the 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>

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

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

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

有什么想法吗?

推荐答案

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

You can try in your input text as below:

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

this will do it without using JavaScript. pattern can be used instead.

对于表单验证,它比JavaScript更为有效.

It is rather effective than JavaScript for form validation.

这篇关于只允许在html textinput中输入某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆