Input pattern, at least 1 non-whitespace character

后端 未结 1 1036
一生所求
一生所求 2021-01-14 07:12

I\'m wanting to rewrite the following as a HTML pattern:

if (/\\S/.test(myString)) {
    // string is not empty and not just whitespace
}

S

相关标签:
1条回答
  • 2021-01-14 07:57

    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]*"
    

    Since you are validating a multiline text (i.e. text containing newline symbols), you need to match them with [\s\S] or with [^] constructs.

    The pattern attribute will work with <input> element only.

    To validate a textarea field, you can create a custom pattern attribute validation:

    $('#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>

    0 讨论(0)
提交回复
热议问题