输入模式,至少 1 个非空白字符 [英] Input pattern, at least 1 non-whitespace character

查看:29
本文介绍了输入模式,至少 1 个非空白字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下内容重写为 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屋!

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