63

我的 html5 表单中有以下输入标记:

<p>
    <label>Company Name*</label>
    <input type="text" name="name" class="field" required pattern="[a-zA-Z0-9]+" />
</p>

这可以很好地检查公司名称是否由字母数字字符组成。但我当然想在公司名称中允许空格。我需要知道我应该在模式中添加什么。

4

8 回答 8

103

如何在模式属性中添加一个空格,例如pattern="[a-zA-Z0-9 ]+". 如果您想支持任何类型的空间,请尝试pattern="[a-zA-Z0-9\s]+"

于 2013-10-27T14:57:11.073 回答
41

我的解决方案是涵盖所有变音符号:

([A-z0-9À-ž\s]){2,}

A-z- 这适用于所有拉丁字符

0-9- 这是所有数字

À-ž- 这适用于所有变音符号

\s - 这是空间

{2,}- 字符串至少需要 2 个字符长

于 2016-10-14T08:34:19.227 回答
10

要避免只有空格的输入,请使用:"[a-zA-Z0-9]+[a-zA-Z0-9 ]+"

eg: abc | abc aBc | abc 123 AbC 938234

例如,为了确保输入名字和姓氏,请使用轻微的变体,例如

"[a-zA-Z]+[ ][a-zA-Z]+"

eg: abc def
于 2015-03-19T16:22:19.940 回答
9

这是一个相当古老的问题,但如果它对任何人都有用,从这里找到的良好响应的组合开始,我已经结束了使用这种模式:

pattern="([^\s][A-z0-9À-ž\s]+)"

它至少需要两个字符,确保它不以空格开头,但允许单词之间有空格,并且还允许特殊字符,例如ą, ó, ä, ö.

于 2018-02-26T18:28:44.900 回答
4

使用此代码确保用户不仅输入空格,而且输入有效名称:

pattern="[a-zA-Z][a-zA-Z0-9\s]*"
于 2015-09-17T17:30:38.320 回答
1

在此处输入图像描述

<h1>In my case, I need only Number and I hafta stop to user entering any Alphabets. We can also stop to entering any number.</h1>

<hr> 
<p>
<h2>Number only</h2>
<input type="tel" name="PhoneNumber" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');" />
</p>
<hr> 
<p>
<h2>Alphabets only</h2>
<input type="text" name="name" onkeyup="this.value=this.value.replace(/[^A-z]/g,'');" />
</p>

于 2021-03-01T05:30:01.817 回答
0

使用如下格式代码

$('#title').keypress(function(event){
    //get envent value       
    var inputValue = event.which;
    // check whitespaces only.
    if(inputValue == 32){
        return true;    
    }
     // check number only.
    if(inputValue == 48 || inputValue == 49 || inputValue == 50 || inputValue == 51 || inputValue == 52 || inputValue == 53 ||  inputValue ==  54 ||  inputValue == 55 || inputValue == 56 || inputValue == 57){
        return true;
    }
    // check special char.
    if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) { 
        event.preventDefault(); 
    }
})
于 2018-06-28T11:35:02.387 回答
0

将以下代码用于 HTML5 验证模式字母数字,不带 / 带空格:-

对于没有空格的 HTML5 验证模式字母数字:- onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"

对于带有空格的 HTML5 验证模式字母数字:-

onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || 事件.charCode == 32"

于 2017-10-24T06:41:27.507 回答