HTML5最小字符长度验证忽略空格和制表符 [英] HTML5 minimum character length validation ignoring spaces and tabs

查看:104
本文介绍了HTML5最小字符长度验证忽略空格和制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用HTML5'pattern'属性和'required'来验证输入框。 HTML5的必需属性可以工作但它可以接受空格和制表符,这是不好的,因为用户只会放置空格。我需要正则表达式,它将接受空格和制表符,但只能计算字符的数量。示例ronny jones这应该给10。

I am using HTML5 'pattern' attribute with 'required' for validation of input boxes. HTML5's required attribute works but it can accept spaces and tabs which is not good because user will just put spaces then. I need regex such that it will accepts space and tabs but able to count only character's. Example "ronny jones" this should give 10.

在javascript中我们使用类似的东西来做,我在HTML5中寻找类似的东西

In javascript we do it using something like this, I am looking for similar thing in HTML5

      var name = document.forms['contact']['name'].value.replace(/ /g,""); // remove whitespace
  if(name.length<6){  // count number of character.
     document.getElementById('message').innerHTML="Enter correct Name";   
     return false;
  }

我在SO上找到了一个相关的问题: HTML5中是否有minlength验证属性?但它接受空格和制表符,我不想要。

I found one related question to this on SO : Is there a minlength validation attribute in HTML5? but it accepts spaces and tabs, which I don't want.

以下是我的HTML5模式代码,

Below is my code with HTML5 pattern,

    <input type="text" name="name" class="form-control" placeholder="Your Full Name" pattern="[A-Za-z]{6,}" title="Name should have atleast 6 characters." required="" />


推荐答案

我管理了一个愚蠢的黑客行为,你做了你的要求:

I managed a silly hack that does what you asked:

<input type="text" name="name" class="form-control" placeholder="Your Full Name" pattern="\s*(\S\s*){6,}" title="Name should have at least 6 characters." required="" />

必须有6个非空格字符才能通过。所以asdfgh,abc def会起作用,但是abc de会失败。

There must be 6 non-space characters for this to pass. so "asdfgh", " abc def " will work, but "abc de" fails.

它不适用于你对安东尼之后有空间的评论因为安东尼包含6个字符,那么它没关系?如果没有,你能否在问题中进一步澄清。

It DOES NOT work for your comment about "there's a space after Anthony" but as Anthony contains 6 characters, then it's fine? If not, can you clarify further in the question.

解释它是如何运作的:


  • 它采用取1个非空格字符的模式 \S 后跟none-or - 更多空格字符 \ s *

  • 您需要将模式匹配6次或更多次 (模式){6,} (\\\ * *){6,}

  • 然后允许前面的非或多个空格 \s *

  • it takes a pattern of "take 1 non-space character" \S followed by "none-or-more space characters" \s*
  • you need the pattern to be matched 6 or more times (pattern){6,} i.e. (\S\s*){6,}
  • then allow non-or-more spaces at the front \s*

如果您想限制仅允许使用Alpha的字符,请将 \S 更改为 [A-Za-z]

If you want to limit the characters allowed to Alpha only, change the \S to [A-Za-z].

是的,这是一个黑客入侵IMO,因为它将在内部解析长字符串。但是这份工作。您可能想与 maxlength 混合以限制它?

Yes, it's a hack IMO as it will be hell to parse internally on long strings. But does the job. You might want to mix with maxlength to limit that as well?

这篇关于HTML5最小字符长度验证忽略空格和制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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