I’m having an issue with TypeScript. i’m doing a Form with a field validator and I’m trying to declare the variable ‘this.username’, however, the browser console is generating the following error: “Uncaught TypeError: Cannot set properties of undefined (setting ‘username’)”, Does anyone have any idea what I need to do?
apparently there are no typing or variable declaration errors. I tried typing the username variable as any but it didn’t work, follow the typescript and HTML:
function validateForm(this: any): void{
this.username = document.querySelector(".username")
this.email = document.querySelector(".email")
this.password = document.querySelector(".password")
this.confirmPassword = document.querySelector(".password2")
this.form = document.querySelector(".form")
this.events = () => {
this.form.addEventListener('submit', (e: any) => {
this.handleSubmit(e);
});
}
this.handleSubmit = (e: any) => {
e.preventDefault();
alert("olá mundo")
}
}
// disable-eslint-line
const validate = new (validateForm() as any)
validate()
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Faça seu registro</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<div class="container">
<form action="" id="form" class="form">
<h2>Faça seu cadastro</h2>
<div class="form-fields">
<label for="username">Seu usuário</label>
<input type="text" name="username" class="username" id="username" placeholder="Seu usuário">
<span class="error-message">Campo inválido por algum motivo qualquer</span>
</div>
<div class="form-fields">
<label for="email">Seu e-mail</label>
<input type="email" name="email" class="email" id="email" placeholder="Seu e-mail">
<span class="error-message">Campo inválido por algum motivo qualquer</span>
</div>
<div class="form-fields">
<label for="username">Sua senha</label>
<input type="password" name="password" class="password" id="password" placeholder="Sua senha">
<span class="error-message">Campo inválido por algum motivo qualquer</span>
</div>
<div class="form-fields">
<label for="username">Repetir senha</label>
<input type="password" name="password2" class="password2" id="password2" placeholder="Repetir senha">
<span class="error-message">Campo inválido por algum motivo qualquer</span>
</div>
<div class="form-fields">
<button type="submit">Enviar</button>
</div>
</form>
</div>
<script src="assets/js/bundle.js"></script>
</body>
</html>
Paulo1706 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.