Reputation: 31
help me, please! How to make the name can only be entered as a string (number, character, anything but not space or an empty space)?
let name = prompt('hi! what is your name?');
while (name == ' ' || name == null) {
name = prompt('please, enter your name');
}
alert(name + ", texttexttext")
Upvotes: 0
Views: 1116
Reputation: 13222
This regex (/^\S*$/
) matches only strings that don't contain whitespace characters. The while loop repeats until the regex is true.
Note: Using prompt and alert is not good for usability. They will freeze up the entire website and annoy most users. I recommend do develop in input using the <input>
element combined with event handlers.
let name = prompt('hi! what is your name?');
while(!/^\S*$/.test(name)) {
name = prompt('please, enter your name');
}
alert(name + ", texttexttext");
The below example shows how you can do it using an input element and html5 validation. A red border is shown when the name is invalid because of the css. When you submit the form the "Invalid name." message will be displayed if the input is not valid.
document.querySelector("#nameinput").addEventListener('change', (e) => {
let value = e.currentTarget.value;
if(!/^\S*$/.test(value)) {
e.currentTarget.setCustomValidity("Invalid name.");
}
else {
e.currentTarget.setCustomValidity("");
}
});
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
<form>
<input id="nameinput" name="name" type="text">
<button type="submit">Submit</button>
</form>
Upvotes: 5