简体   繁体   中英

white space regex in javascript

I have written a HTML 5 file. In form I have one required text field. I want to validate this text field in such way that user can start the value in it with a space. But he is not allowed to enter only a space character. Means, he can start typing with a space but must not enter only a space character in text field. To work around this, I gave a pattern attribute through javascript's setAttribute method.

<form method="post" action="" id="validation">
    Name:<input type="text" id="nome"  name="nome" required="required" oninvalid="this.setCustomValidity('Name is required field')" oninput="setCustomValidity('')" /><br />
<br><br>

        <input type="submit" value="Enviar" />
    </form>
<script>
document.getElementById('nome').setAttribute("pattern",".*\S+.*");
</script>   

output: when I gave only space. It works. But when I start typing with a space and then some characters, then It again validates: "Name is required field.", whereas now it should mark it correct. one more thing, I want to add the pattern attribute through javascript only. How can I resolve this problem in such a way that when user can start typing with a space but should not be allowed to enter only a space.

The minimal pattern you need is

^ *[^ ]+.*$

If you want to ask for exact non-space characters in the middle (for example, 5 or more) of a string then use

^ *[^ ]{5,}.*$

Notice that the above patterns are indifferent to spaces in the end of matching strings, and if you want to forbid trailing spaces then remove the .* part.

Also if nessesary you may change the space character to \\s everywnere in these examples to catch also tabs, carriage return, form feed etc. characters.

It seems you simply want to prevent the user from entering only space characters. You could try simply trimming an instance of the input. It would be more reliable than using a RegEx for this scenario.

If the trimmed instance comes to have null length, then the user entered only space characters. Then you can return an "invalid" error.

Here is an example of the logic:

if(string.trim().length === 0) {
  return false;
}

Here is a fiddle: http://jsfiddle.net/esvsLx8u/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM