ditto
ditto

Reputation: 6287

Input pattern, at least 1 non-whitespace character

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

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

So

<input pattern="\S" required">

if ($('form :invalid'))
    console.log('empty');
else
    console.log('has non-whitespace char');

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.

Upvotes: 5

Views: 6839

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627020

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>

Upvotes: 7

Related Questions