Issue
I have a problem with regex.
In my code I have an input when a player can write his name and then click the 'start'
button to start the adventure.
The first condition is working fine. The player gets an error when the name isn't between 4 and 20 characters long.
When it comes to the next condition. The player gets an error no matter what will he write inside the input. When I changed the match()
to test()
there is an error in console, that the test()
is not a function.
Please help me, what did I do wrong?
let actualPlace = 'mainMenu';
let playerName = '';
const playerNameContainer = document.querySelector('.playerName');
const start = document.querySelector('.start');
const regExpression = /^[a-zA-ZżźćńółęąśŻŹĆĄŚĘŁÓŃ0-9]$/;
start.addEventListener('click', function(){
if (actualPlace == 'mainMenu') {
playerNameValue = playerNameContainer.value;
playerNameLength = playerNameValue.length;
if (playerNameLength >= 4 && playerNameLength <= 20) {
if (playerNameValue.match(regExpression)) {
actualPlace = 'adventure';
playerName = playerNameContainer.value;
playerNameContainer.value = '';
} else {
errorMsg.innerHTML = 'error';
}
} else {
errorMsg.innerHTML = 'error';
}
}
})
Solution
your regular expression is matching only one single character; you need to add the +
quantifier to match more than one character.
I also added different errors so you know what part is failing
Here its a working example:
let actualPlace = 'mainMenu';
let playerName = '';
const playerNameContainer = document.querySelector('.playerName');
const start = document.querySelector('.start');
const regExpression = /^[a-zA-ZżźćńółęąśŻŹĆĄŚĘŁÓŃ0-9]+$/;
const errorMsg = document.querySelector('.error');
start.addEventListener('click', function(){
if (actualPlace == 'mainMenu') {
playerNameValue = playerNameContainer.value;
playerNameLength = playerNameValue.length;
if (playerNameLength >= 4 && playerNameLength <= 20) {
if (playerNameValue.match(regExpression)) {
actualPlace = 'adventure';
playerName = playerNameContainer.value;
playerNameContainer.value = '';
errorMsg.innerHTML = 'Success!';
} else {
errorMsg.innerHTML = 'error: your name must not contain spetial characters';
}
} else {
errorMsg.innerHTML = 'error: your name must be between 4 and 20 characters';
}
}
})
<input class="playerName" /><br />
<button class="start" >Start</button>
<div class="error" ></div>
Answered By - Daniel Cruz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.