HTML 简单不空白模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13199606/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:41:19  来源:igfitidea点击:

HTML simple not blank pattern

regexhtml

提问by Point89

I have a simple form and i want the submit button not to work for the conditions i give in the pattern, but if i leave it blank the submit works. how can i make the pattern not to accept it if it is blank?

我有一个简单的表单,我希望提交按钮不适合我在模式中给出的条件,但如果我将其留空,则提交工作。如果它是空白的,我怎样才能让模式不接受它?

<form action="test.php" method="POST">
Enter user name: 
<input type="text" name="username" pattern="[A-Za-z0-9]{1,20}">
<input type="submit" value="submit">
</form>

I thought the {1,20} is enought but it seems it's not.

我认为 {1,20} 已经足够了,但似乎不是。

回答by feeela

HTML has the requiredattribute to accomplish this. If you set any input to be required, modern browsers won't let you submit the form if those fields are empty.

HTML 具有required完成此操作的属性。如果您将任何输入设置为必填项,并且这些字段为空,现代浏览器将不允许您提交表单。

<input type="text" name="username" required="required" pattern="[A-Za-z0-9]{1,20}">

回答by Patrick Kenekayoro

To prevent errors from showing on load, you can not use the HTML5 required attribute. You can use Javascript. For example

为防止加载时显示错误,您不能使用 HTML5 required 属性。您可以使用 JavaScript。例如

    if( $('#form-password').val() == "" ) 
    {
        e.preventDefault();
    }

Using HTML Patterns to match at least one.

使用 HTML 模式匹配至少一个。

    <input type="text" name="username" pattern=".{1,}">