Search code examples
javascriptfunctionvalidationfor-loopprompt

prompt user to enter string which is free of special characters [@ . , !] Javascript


In my code the problem is that it validates at first wrong input and then tells the user to enter again but when the user again enters wrong its validation fails and says alert "correct in"

Write a program to take user input and store username in a variable. If the username contains any special symbol among [@ . , !], prompt the user to enter a valid username. For character codes of [@ . Note: ASCII code of ! is 33 ASCII code of , is 44 ASCII code of . is 46 ASCII code of @ is 64

var userName=prompt("Enter your Input: ");
checkValidName(userName);
function checkValidName(un)
{
    var message;
    var split=[];
    var arr=[];
    for(var i=0;i<un.length;i++)
    {
        split[i]=un.split("&nbsp;");
        arr[i]=un.charCodeAt(i);
        if(arr[i]!=33||arr[i]!=44||arr[i]!=46||arr[i]!=64)
        {
                message="Correct User Name";
        }
        while(arr[i]==33||arr[i]==44||arr[i]==46||arr[i]==64)
        {
            alert("please enter a valid userName");                                                                                                                   
            userName=prompt("Enter your Input: ");
            split[i]=un.split("&nbsp;");
            arr[i]=un.charCodeAt(i);
            if(arr[i]!=33||arr[i]!=44||arr[i]!=46||arr[i]!=64)
            {
                message="correct in";
                break;
            }
        }

    }
    alert(message);
}

Solution

  • Rather than asking inside the function that validates, I'd have a loop that uses that function:

        var userName=prompt("Enter your Input: ");
        while (!checkValidName(userName)){
            alert("please enter a valid userName");   
            userName=prompt("Enter your Input: ");
        };
    

    (Now you need to return true or false in your checkValidName(userName) code)

    EDIT: regarding the function itself, looking at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match I think you can use

    const checkValidName = (username) => username.match(/[\@\.\,\!]/)===null;