jQuery 如何强制输入只允许字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19508183/
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
How to force input to only allow Alpha Letters?
提问by Leon Gaban
using jQuery here, however unable to prevent numbers from being typed into the input field
在这里使用 jQuery,但是无法阻止将数字输入到输入字段中
http://codepen.io/leongaban/pen/owbjg
http://codepen.io/leongaban/pen/owbjg
Input
输入
<input type="text" name="field" maxlength="8"
title="Only Letters"
value="Type Letters Only"
onkeydown="return alphaOnly(event);"
onblur="if (this.value == '') {this.value = 'Type Letters Only';}"
onfocus="if (this.value == 'Type Letters Only') {this.value = '';}"/>
jQuery
jQuery
function alphaOnly(event) {
alert(event);
var key;
if (window.event) {
key = window.event.key;
} else if (e) {
key = e.which;
}
//var key = window.event.key || event.key;
alert(key.value);
return ((key >= 65 && key <= 90) || (key >= 95 && key <= 122));
}
I've seen plenty of examples here on how to restrict to only Numbers, and I'm using the correct key codes for a-z and A-Z. Do you see what I'm doing wrong?
我在这里看到了很多关于如何仅限于数字的示例,并且我使用了正确的 az 和 AZ 键码。你看到我做错了什么吗?
采纳答案by hexacyanide
The property event.key
gave me an undefined value. Instead, I used event.keyCode
:
该属性event.key
给了我一个未定义的值。相反,我使用了event.keyCode
:
function alphaOnly(event) {
var key = event.keyCode;
return ((key >= 65 && key <= 90) || key == 8);
};
Note that the value of 8 is for the backspace key.
请注意,值 8 用于退格键。
回答by Kamil Kie?czewski
Short ONELINER:
短ONELINER:
<input onkeypress="return /[a-z]/i.test(event.key)" >
For all unicode letterstry this regexp: /\p{L}/u
(but... this) - and here is working example:)
回答by Robin Keskisarkka
Rather than relying on key codes, which can be quite cumbersome, you can instead use regular expressions. By changing the pattern we can easily restrict the input to fit our needs. Note that this works with the keypress
event and will allow the use of backspace (as in the accepted answer). It will not prevent users from pasting 'illegal' chars.
您可以使用正则表达式,而不是依赖可能非常麻烦的键代码。通过更改模式,我们可以轻松地限制输入以满足我们的需求。请注意,这适用于该keypress
事件,并允许使用退格键(如已接受的答案)。它不会阻止用户粘贴“非法”字符。
function testInput(event) {
var value = String.fromCharCode(event.which);
var pattern = new RegExp(/[a-z??? ]/i);
return pattern.test(value);
}
$('#my-field').bind('keypress', testInput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
Test input:
<input id="my-field" type="text">
</label>
回答by Dustin Spengler
Nice one-liner HTML only:
仅漂亮的单行 HTML:
<input type="text" id='nameInput' onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'>
回答by jsbisht
On newer browsers, you can use:
在较新的浏览器上,您可以使用:
<input type="text" name="country_code"
pattern="[A-Za-z]" title="Three letter country code">
You can use regular expressions to restrict the input fields.
您可以使用正则表达式来限制输入字段。
回答by Pankaj Upadhyay
<input type="text" name="field" maxlength="8"
onkeypress="return onlyAlphabets(event,this);" />
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
回答by decoder7283
A lot of the other solutions that use keypresswill not work on mobile, you need to use input.
许多其他使用keypress 的解决方案在移动设备上不起作用,您需要使用input。
html
html
<input type="text" id="name" data-value="" autocomplete="off" spellcheck="true" placeholder="Type your name" autofocus />
jQuery
jQuery
$('#name').on('input', function() {
var cursor_pos = $(this).getCursorPosition()
if(!(/^[a-zA-Z ']*$/.test($(this).val())) ) {
$(this).val($(this).attr('data-value'))
$(this).setCursorPosition(cursor_pos - 1)
return
}
$(this).attr('data-value', $(this).val())
})
$.fn.getCursorPosition = function() {
if(this.length == 0) return -1
return $(this).getSelectionStart()
}
$.fn.setCursorPosition = function(position) {
if(this.lengh == 0) return this
return $(this).setSelection(position, position)
}
$.fn.getSelectionStart = function(){
if(this.lengh == 0) return -1
input = this[0]
var pos = input.value.length
if (input.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', input.value.length)
if (r.text == '')
pos = input.value.length
pos = input.value.lastIndexOf(r.text)
} else if(typeof(input.selectionStart)!="undefined")
pos = input.selectionStart
return pos
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
if(this.lengh == 0) return this
input = this[0]
if(input.createTextRange) {
var range = input.createTextRange()
range.collapse(true)
range.moveEnd('character', selectionEnd)
range.moveStart('character', selectionStart)
range.select()
}
else if (input.setSelectionRange) {
input.focus()
input.setSelectionRange(selectionStart, selectionEnd)
}
return this
}
回答by gopinath
<input type="text" name="name" id="event" onkeydown="return alphaOnly(event);" required />
function alphaOnly(event) {
var key = event.keyCode;`enter code here`
return ((key >= 65 && key <= 90) || key == 8);
};