简体   繁体   English

jQuery仅在按键时允许字符之间留有空格

[英]Jquery Allow Empty space between Characters only on Key press

Hi how to allow empty characters between words only. 嗨,如何只允许单词之间留空字符。 I have tried but doesn't allow empty character anywhere. 我已经尝试过,但不允许在任何地方使用空字符。

Jquery jQuery的

  $('#txtName').keypress(function (e) { var regex = new RegExp("^[a-zA-Z0-9_ ]*$"); var str = String.fromCharCode(!e.charCode ? e.which : e.charCode); if (regex.test(str)) { return true; } else { e.preventDefault(); alert('Please Enter Alphabet'); return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="txtName"> 

It's for name validation. 它用于名称验证。 Thanks. 谢谢。

Use this pattern: 使用以下模式:

/(\s{2,})|[^a-zA-Z']/g

 $('#txtName').keypress(function(e) { var $this = $(this); $(this).val($this.val().replace(/(\\s{2,})|[^a-zA-Z0-9_']/g, ' ').replace(/^\\s*/, '')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="txtName" /> 

From JSFiddle JSFiddle

use Trim() method, with this method you can remove any space in first and last of your string, then put equal to null or white-space Online demo 使用Trim()方法,使用此方法,您可以删除字符串的开头和结尾的任何空格,然后将其放置为等于nullwhite-space 在线演示

if you want just Regex with /^[\\s\\\xA0]+|[\\s\\\xA0]+$/g you can get any white-space in first and last of your string then out not equal to null or white-space Demo 如果只想使用/^[\\s\\\xA0]+|[\\s\\\xA0]+$/g正则表达式,则可以在字符串的/^[\\s\\\xA0]+|[\\s\\\xA0]+$/g获取任何空格,然后输出不等于nullwhite-space 演示

for more information see this 有关更多信息,请参阅

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在按键事件中仅允许特定打印范围内的字符? - How to allow only characters on key press event for specific print range? 正则表达式不允许在开头和结尾使用空格,并且在字符之间仅允许一个空格 - regex to disallow space at begining and end and allow only one space between characters 输入文本框字段仅允许字符,不允许数字,但允许空格? - Input textbox field allow only characters not allow numeric but allow space? jQuery只允许使用拉丁字符 - jQuery only allow latin characters 仅对空白空间进行RegEx验证; 应该接受单词/字符之间的空格 - RegEx validation for only empty space; should accept space between words/characters 正则表达式,只允许字符或空格 - Regular expression which allow only characters or space 如何按空格键,然后在文本区域中按Backspace键:使用JQuery? - How to press space key and then backspace key in a textarea: using JQuery? 正则表达式只允许单词之间有一个空格 - regexp to allow only one space in between words 我想检查仅允许空格、AZ、az、0-9 的文本字段上的按键或按键事件中特殊字符的验证 - I want to check validation of special character on key-press or key-up event on a text field which allow space,A-Z,a-z,0-9 only 只允许特殊字符和数字-jQuery - Allow only special characters and numbers - jQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM