输入模式,至少 1 个非空白字符 [英] Input pattern, at least 1 non-whitespace character
问题描述
我想将以下内容重写为 HTML 模式:
I'm wanting to rewrite the following as a HTML pattern:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
所以
<input pattern="\S" required">
if ($('form :invalid'))
console.log('empty');
else
console.log('has non-whitespace char');
问题是我的模式与测试字符串的工作方式不同.我想检查是否至少有 1 个非空白字符.
The problem is my pattern doesn't work the same as the test string. I'm wanting to check if there is at least 1 non-whitespace character.
推荐答案
pattern
属性需要全字符串匹配,模式自动锚定(无需使用^
和 $
).因此,要要求至少 1 个非空格,请使用
The pattern
attribute requires full string match and the pattern is automatically anchored (no need to use ^
and $
). Thus, to require at least 1 non-whitespace, use
pattern="[\s\S]*\S[\s\S]*"
由于您正在验证多行文本(即包含换行符的文本),您需要将它们与 [\s\S]
或 [^]
结构匹配.
Since you are validating a multiline text (i.e. text containing newline symbols), you need to match them with [\s\S]
or with [^]
constructs.
pattern 属性仅适用于 <input>
元素.
要验证textarea字段,您可以创建自定义pattern
属性验证:
$('#test').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
var hasError = !$(this).val().match(pattern); // check if the line matches the pattern
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else { // Not supported by the browser, fallback to manual error display
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
}
:valid, .ok {
background:white;
color: green;
}
:invalid, .error {
background:yellow;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<textarea name="test" pattern="[\S\s]*\S[\S\s]*" id="test"></textarea>
<input type="submit" />
</form>
这篇关于输入模式,至少 1 个非空白字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!