Reputation: 1724
I need to write a regular expression for form validation that allows spaces within a string, but doesn't allow only white space.Example, if the user just enter spaces, it should trigger javascript alert
I tried this but this not work
<script>
if (document.getElementsByClassName('notes') == " ") {
alert("Notes should not begin with space");
}
}
html
<textarea name="notes" class="form-control" class="notes"></textarea>
Upvotes: 0
Views: 1687
Reputation: 27202
Try this it is working fine :
HTML :
<textarea name="notes" class="form-control notes"></textarea>
Script :
$('textarea').on('keyup', function(){
if (document.getElementsByClassName('notes')[0].value[0] == " ") {
alert("Notes should not begin with space");
}
});
Demo : https://jsfiddle.net/fer49eby/
Upvotes: 0
Reputation: 1724
Ok I got it. All answers above are correct, but I have to add "onclick" event on submit
<input type="submit" name="submit" class="btn btn-primary btn-default" value="submit" onclick="return showAlert()">
js
<script>
function showAlert(){
if (document.getElementsByClassName('notes')[0].value[0] == " ") {
alert("Notes should not begin with space");
return false;
}
}
Upvotes: 0
Reputation: 593
Please check your HTML. There are two class attributes:
<textarea name="notes" class="form-control" class="notes"></textarea>
Combine them first :
<textarea name="notes" class="form-control notes"></textarea>
Now the selector
document.getElementsByClassName('notes')[0]
should give you the target element.
Upvotes: 1
Reputation: 477
You are comparing the array of elements that document.getElementsByClassName returns to " ", which will obviously be false, you want to compare the value of the element.
if (document.getElementsByClassName('notes')[0].value[0] == " ") {
alert("Notes should not begin with space");
}
In this example, the .value
returns the value of the textarea, and .value[0]
means the first char of the value
Upvotes: 1
Reputation: 9743
You need to get the value
of input
like:
if (document.getElementsByClassName('notes')[0].value == "") {
alert("Notes should not begin with space");
}
Ps. The getElementsByClassName
will return a list of elements. So,when compared with " "
will always return false
.
Upvotes: 1
Reputation: 8354
if (document.getElementsByClassName('notes') == " ")
getElementsByClassName()
returns a collection of nodes not value of node , use []
and value
property along with trim()
.
if(document.getElementsByClassName('notes')[0].value.trim() === "")
Upvotes: 1