简体   繁体   English

用于HTML表单验证的正则表达式开始时没有空格

[英]Regex for HTML form validation start without space

I have a form field in which I want to allow 1 to 50 letters, numbers, and spaces in it. 我有一个表单域,我想在其中允许1到50个字母,数字和空格。 Just not start with a space and ends with a space. 只是不能以空格开头,而不能以空格结尾。 (Or, alternatively, if it starts with a space, it's not counted toward 50.) (或者,如果以空格开头,则不计入50。)

I have something like: 我有类似的东西:

^[^s][a-zA-Z0-9_ ]{1,50}[^s]$

But something like "AB" now doesn't pass, because nothing match the {1,50}. 但是像“ AB”之类的东西现在无法通过,因为没有匹配{1,50}的东西。

EDIT: 编辑:

The regex is for the HTML input element pattern field. 正则表达式用于HTML输入元素pattern字段。

Try this 尝试这个

^\b[\w ]{1,50}\b$

Demo 演示版

My comment as an answer ;) 我的评论作为答案;)

^\s*[a-zA-Z0-9_ ]{1,50}\s*$

This regex will allow entry of white space in the beginning and at the end without requiring it as your attempt (kind of) did. 此正则表达式将允许在开头和结尾输入空白,而无需像您的尝试(那样)那样。

Regards 问候

Edit: 编辑:

Combine Tims answer with this and you avoid space only : 结合Tims的答案,就可以避免空格

^\s*\b[\w ]{1,50}$\s*

This forces the string to have a word boundary - ie must contain a word character . 这将强制字符串具有单词边界-即必须包含单词字符

Or with minimal use of regex: 或最少使用正则表达式:

 function myFunction() { var input = document.getElementById('myInput').value.trim(); if (input.length < 1 || input.length > 50) { document.body.innerHTML += "wrong lenth"; return false; } var re = /^[\\w ]+$/; if (re.exec(input) !== null) { document.body.innerHTML += input + " is valid"; return true; } else { document.body.innerHTML += input + " is not valid"; return false; } } 
 <input id="myInput"> <button onclick="myFunction()">Test</button> 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM