Checking and validating names using Javascript

I am working to script for validating  and checking names, I found out a script, I adapted a little bit, and I tried to add two arrays, a for...of loop and an if...else statemet to show two different messages, one for taken names and the other for available names, but something went wrong, my code did not work and the mesage from else statement is shown on the page.
What I did wrong?
Below the script, my lines are from //--to check, not working...
//reload whole page
function backToFuture() {
    window.location='index.html';
}
(function checkName() {
	
	const wantedNames = document.getElementById('desiredNames');
	const	form = document.getElementById('form');
	const	elem = document.createElement('div');
			elem.id = 'notify';
			elem.style.display = 'none';

			form.appendChild(elem);

	wantedNames.addEventListener('invalid', function(event){
		event.preventDefault();
		if ( ! event.target.validity.valid ) {
			wantedNames.className    = 'invalid animated shake';
			elem.textContent   = 'Name can have only small letters, number and sign - (minus), min.3 ans max.35 characters, ie. ionel-74';
			elem.className     = 'error';
			elem.style.display = 'block';
		}
	});

	wantedNames.addEventListener('input', function(event){
		if ( 'block' === elem.style.display ) {
			wantedNames.className = '';
			elem.style.display = 'none';
		}
	});
//--to check, not working....

	const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
	const reservedNames=['cristina','angela','rusanda','costantin'];
	const givenNames=[...takenNames, ...reservedNames];
	
	for( const givenName of givenNames) {
		if(wantedNames===givenName) {
			greetings= wantedNames +" not available. Try again!";
		} else {
			greetings= "Available name!";
		}
		document.getElementById("available").innerHTML=greetings;
	};

})();

Open in new window


Below the html code
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Name Validation</title>
  
  
  <link rel='stylesheet prefetch' href='css/animate.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>
  <form id="form">
		<label for="desiredNames">Name to be checked</label>
		<input name="desiredNames" type="text" placeholder="insert-name-here"  pattern="\b[a-z0-9-]{3,35}\b" id="desiredNames"><br>
		<button onclick="checkName()">Check Name</button><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><button onclick="backToFuture()">Try again&nbsp;</button><br>
		<p id="available"></p>
		<p id="ocupat"></p>

</form>
  
    <script  src="js/index.js"></script>

</body>
</html>

Open in new window

Manuel-Remus StancaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
What are you trying to do here?

Your for loop is located in the body of the (function() which means it is going to run on page load only - never again - yet in the loop you are doing a check against wantedNames which is an HTML element

If you want to check if wantedNames value is equal to something you need to use wantedNames.value - but even if you change your loop to use that it still does not make sense because the loop is running before anything is put into wantedNames.

If you want to only allow not used names then you need to do this
//reload whole page
function backToFuture() {
    window.location='index.html';
}
(function checkName() {
  
  const wantedNames = document.getElementById('desiredNames');
  const  form = document.getElementById('form');
  const  elem = document.createElement('div');
      elem.id = 'notify';
      elem.style.display = 'none';

      form.appendChild(elem);

  wantedNames.addEventListener('invalid', function(event){
    event.preventDefault();
    if ( ! event.target.validity.valid ) {
      wantedNames.className    = 'invalid animated shake';
      elem.textContent   = 'Name can have only small letters, number and sign - (minus), min.3 ans max.35 characters, ie. ionel-74';
      elem.className     = 'error';
      elem.style.display = 'block';
    }
  });

  // BIND TO THE change EVENT
  wantedNames.addEventListener('change', function(event){
    // CHECK THE VALUE OF THE CONTROL
    // CHANGE TO LOWER CASE TO ELIMINATE CASE ISSUES
    // AND CHECK IF IT IS IN THE givenNames ARRAY
    if (givenNames.indexOf(this.value.toLowerCase()) > -1) {
      // AGAIN USE THE .value TO GET THE VALUE
      greetings= this.value +" not available. Try again!";
    }
    else {
      greetings= "Available name!";
    }
    document.getElementById("available").innerHTML=greetings;

    // NOT SURE WHAT THE INTENTION WITH THIS IS
    /*
    if ( 'block' === elem.style.display ) {
      wantedNames.className = '';
      elem.style.display = 'none';
    }
    */
  });
//--to check, not working....

  const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
  const reservedNames=['cristina','angela','rusanda','costantin'];
  const givenNames=[...takenNames, ...reservedNames];
  
  /* THIS CODE DOES NOTHING USEFUL
  for( const givenName of givenNames) {
  console.log('fired');
    if(wantedNames===givenName) {
      greetings= wantedNames +" not available. Try again!";
    } else {
      greetings= "Available name!";
    }
    document.getElementById("available").innerHTML=greetings;
  };
  */

})();

Open in new window

Manuel-Remus StancaAuthor Commented:
Hi Julian,

I checked it and it worked partially. When I put a name that is not taken neither reserved which starts or ends with the sign - (minus), appears the popup warning that mention is not allowed to use it, but also appears the " Available name" message. (it must be only that popup  warning message).  When I put a name that is reserved or taken, the message  "name variable is not available. Try again" appears for a very short time, and then disappears, but that message is supposed to stay on the page (at least the user leave the page or try another name).
I attached some pictures (if any info required, please let me know)
Could you check, please?

Thx for helping me!
dash-desiredName.PNG
dash-reservedName.PNG
reservedName.PNG
desiredName.PNG
Julian HansenCommented:
I have no idea what the specification is here - hence my original question.

The code you posted initially did not make any kind of sense and only loosely gave an inclination of what it is you are trying to achieve.

Please explain the exact behaviour you are trying to create (but without reference to the code).

Are you asking about the JavaScript or the validation rule (pattern) included as part of the input?

Bear in mind that the validation (pattern) you are using is not totally browser compatible - it does require IE 10 or higher just in case there is a requirement to support older browsers.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Manuel-Remus StancaAuthor Commented:
Hi Julian,

I want to make a script for checking and validating names for choosing subdomains' names.
As I know a subdomain's name is allowed to have only small letters, numbers, and sign minus - , and is not allowed to start and end with sign minus.
I found on the net the first script that checks characters and adds a popup warning if requirements are not fulfilled.  I put a regex pattern into input tag for checking the characters.
The full script has to do as follows:
1. to check characters of the desired name taken from input tag. If characters are ok, then script executes step 2. If characters are not ok (special characters, capital letters, starting or ending with sign minus- - ), then the popup warning shall appear and the user has to refresh the page and return to the point zero.
2. If characters are ok, the name shall be checked against names from two arrays (taken names and reserved names) concatenated into a single array. (it is not mandatory, but I want to have a clear picture of taken and reserved names). If the desired name is equal to a taken or reserved name, then a message should appear  (This name is already taken. Try another one!)- or similar to it-, if the desired name is not equal to a taken or reserved name then a message should appear (This name is available for you! Greetings!) . Both messages shall be put in the paragraph below the buttons and to stay on the page as long as user leave the page or make another trial.
I read about arrays, loops, statement, spread operator, and so on but I am not so good at javascript. I am able to read it and to make some small changes.
I hope that I made myself understood (as much as possible).

Thx again for your patience.

Manuel
Julian HansenCommented:
Any reason you don't want to do the validation (- sign) and name check in the same routine?

In other words - trigger on change, get the name entered check if it is a valid name then check if it has been used?

Also do you specifically want the page to refresh if it is not correct - why not simply clear the form?
Manuel-Remus StancaAuthor Commented:
Hi Julian

For me it is important the final result,
1.valid name and not been used or
2.valid name but been used or
3.not-valid name
and for the valid names no to start or to end with a minus sign, if possible and to have the posibiity to clear the form or to refresh de page.

That is the reason for trying to combine those script, but my knowledge about javascript are at beginner level.

Thx again
Manuel
Julian HansenCommented:
Here is an example of what I think you want

You will notice I have kept the input validation but amended the rule to allow for the valid names. I have also added this check to the change event handler
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Name Validation</title>
  
  
  <link rel='stylesheet prefetch' href='css/animate.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>
  <form id="form">
    <label for="desiredNames">Name to be checked</label>
    <input name="desiredNames" type="text" placeholder="insert-name-here"  pattern="^[a-z][a-z0-9-]{3,34}$/" id="desiredNames"><br>
    <button onclick="checkName()">Check Name</button><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><button onclick="backToFuture()">Try again&nbsp;</button><br>
    <p id="available"></p>
    <p id="ocupat"></p>

</form>
  
<script>
//reload whole page
function backToFuture() {
    window.location='index.html';
}

function checkName()
{
}

(function() {
  
  var errMessage = '';
  
  const takenNames=['manuel','remus','manuel-remus','tomi','mirel'];
  const reservedNames=['cristina','angela','rusanda','costantin'];
  const givenNames=[...takenNames, ...reservedNames];
  const wantedNames = document.getElementById('desiredNames');
  const  form = document.getElementById('form');
  const  elem = document.createElement('div');
  elem.id = 'notify';
  elem.style.display = 'none';

  form.appendChild(elem);

  wantedNames.addEventListener('invalid', function(event){
    event.preventDefault();
    if ( ! event.target.validity.valid ) {
      wantedNames.className    = 'invalid animated shake';
      elem.textContent   = 'Name can have only small letters, number and sign - (minus), min.3 ans max.35 characters, ie. ionel-74';
      elem.className     = 'error';
      elem.style.display = 'block';
    }
  });

  wantedNames.addEventListener('change', function(event){
    if (this.value.match(/^[a-z][a-z0-9-]{3,34}$/)) {
      if (givenNames.indexOf(this.value.toLowerCase()) > -1) {
        errMessage = this.value +" not available. Try again!";
      }
      else {
        errMessage = "Available name!";
      }
    }
    else {
      errMessage = 'Name can have only small letters, number and sign - (minus), min.3 ans max.35 characters, ie. ionel-74';
    }
    document.getElementById("available").innerHTML = errMessage;
  });
})();
</script>
</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Manuel-Remus StancaAuthor Commented:
Hi Julian

It works, thx.
Now  I can adapt it to my native language.

Have a nice day!

Manuel
Manuel-Remus StancaAuthor Commented:
Hi Julian


It works.

Thx and have a nice day!
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
arrays

From novice to tech pro — start learning today.