Reputation: 127
I am trying to validate if the contenteditiable value has only whitespace/blank space. In my example if the value have only whitespace/blank space it should not match according to my regex string, but it not working as intended. It keeps matching when I enter complete blank spaces.
edit: the black space is where you can enter text.
https://jsfiddle.net/j1kcer26/5/
JS
var checkTitle = function() {
var titleinput = document.getElementById("artwork-title").innerHTML;
var titleRegexp = new RegExp("^(?!\s*$).+"); //no blank spaces allowed
if (!titleRegexp.test(titleinput)) {
$('.start').removeClass('active-upload-btn');
console.log('no match')
} else if (titleRegexp.test(titleinput)) {
$('.start').addClass('active-upload-btn');
console.log('match')
}
};
$('#artwork-title').on('keyup change input', function() {
checkTitle();
});
HTML
<div class="post-title-header">
<span class="user-title-input title-contenteditable maxlength-contenteditable" placeholder="enter text here" contenteditable="true" name="artwork-title" id="artwork-title" autocomplete="off" type="text" spellcheck="false">
</span>
</div>
<div class="start">
turn red if match
</div>
Upvotes: 0
Views: 155
Reputation: 78860
If you look at the actual inner HTML, you'll see things like <br>
elements or
entities. Your regex doesn't look equipped to handle these.
You may want to consider using textContent
instead of innerHTML
if you just care about the text, not the HTML. Or alternatively, if you really want plain text, use a <textarea/>
instead of a content-editable div, which is for rich-text-style editing that produces HTML.
Edit:
Your regex is not quite right either. Because you're using the RegExp
constructor with new RegExp("^(?!\s*$).+")
, the \s
in your string literal is going to turn into a plain s
; you have to use a \\s
if you want the regex to have an actual \s
in it. IMO, it's always better to use a regexp literal unless you're building one dynamically, like /^(?!\s*$).+/
, or I find this to be a simpler alternative to tell you if a string is entirely whitespace: /^\s+$/
.
Upvotes: 3