let userdetails = {};
document.getElementById("btn1").onclick = function() {
let username = prompt("enter name pleas")
while (!isNaN(username)) {
username = prompt("enter valid user name not numbers")
}
while (username.length < 3)
username = prompt("enter valid name ")
while (username.length > 8)
username = prompt("enter valid name pleas between 1 to 8")
let age = prompt("enter your age ")
ageval = age.parseInt
while (age < 16 || age > 100)
age = prompt("enter valid age between 16 to 120")
while (String(age))
age = prompt("enter numbers")
i want if user clicking the onclick me button he will get promt that asks from her her name if the name is correct between 1 -8 lengh will not contain a numbers .
if this incorrect the user will get again the prompt "enter valid name , not numbers "
if till he not enters valid name he will get it again and again if in the end he enterd correct name the name will be stored in the userdetails{} . this works but the age getting me problems i will be happy to get help . there is the code ;
i want the age the same age cant contain letters and age should be between 16 -120
if incorrect i want the while loop work till he enters correct age
2
Answers
Don’t use separate
while
loops for each condition. Use a single loop that checks all the requirements of that input.There are few issues.
If you are using condition1 and condition2 sequentially and input1 satisfied condition1 then in next iteration, it will only check with condition2.
So, you should check all conditions for all the inputs.
Second, we already have some validators in HTML form, why not use them?
I would write a validator in the document itself.
So, here is first solution which still uses while loop and prompt.
I have taken liberty of refactoring it a little bit.
Now, for second solution, lets use form elements.
This approach should be lot more convenient to use for any further step.
Unless you have a very specific scenario.