我想将以下内容重写为HTML模式:
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');问题是我的模式不像测试字符串那样工作。我想检查一下是否至少有一个非空白字符。
发布于 2015-12-04 13:17:39
pattern属性需要完全字符串匹配,并且模式自动锚定(不需要使用^和$)。因此,若要要求至少有一个非空白,请使用
pattern="[\s\S]*\S[\s\S]*"由于您正在验证多行文本(即包含换行符的文本),因此需要将它们与[\s\S]或[^]结构匹配。
<input> pattern 属性只适用于元素。
要验证 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>
https://stackoverflow.com/questions/34089232
复制相似问题