Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
Error message not displaying on Form validation

I am creating a simple form with validation with html razor and javascript. One validation that I have is to check for empty fields.

Expected Result:
Error message to be displayed (below the input field) if the user clicks the Submit button without entering any value in the input field.

Actual Result:
No error message displayed even if the user clicks the Submit button without entering any value in the input field. It seems like the html file is not communicating with the JS file at all. I tried various ways such as clearing browser cache and checking for typos, but to no avail.

Here are the relevant codes:

form.cshtml

@* Display error message *@
<div id="error"></div>

<form id ="form">
    <div class="form-group">
        <label for="deviceId">Device ID</label>
        <input type="text" class="form-control" id="deviceId" placeholder="Enter Device Device ID">
    </div>
    
    @* Energy Usage *@
    <div class="form-group">
        <label for="energyUsage">Energy Usage</label>
        <input type="number" class="form-control" id="energyUsage" placeholder="Enter Energy Usage">
    </div>
    
    <button onclick="performValidation()" type="submit">Submit</button>
</form>

@section Scripts
{
    <script src="js/validation.js"></script>
}

validation.js

const deviceId = document.getElementById('deviceId')
const energyUsage = document.getElementById('energyUsage')
const form = document.getElementById('form')
const errorElement = document.getElementById('error')

function performValidation()
{
    form.addEventListener('submit', (e) => {

        // list to store the error messages
        let messages = []

        // if device ID field is an empty string or user did not pass in any device Id
        if (deviceId.value === ' ' || deviceId.value == null) {
            // send the error message
            messages.push('Device ID is required')
            // console.log('No Device ID retrieved')
        }

        // if there is error, prevent the form from submitting
        if (messages.length > 0) {
            e.preventDefault()

            // check errorElement
            errorElement.innerText = messages.join(', ') // to separate error elements from each other
        }
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Remove the space when checking for empty string:

validation.js

if (deviceId.value === '' || deviceId.value == null)

to route the html file to js file correctly:

form.cshtml

<script src="~/js/validation.js"></script>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda