'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
}
})
}
Solution 1:[1]
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>
Solution 2:[2]
Just create that as
..., usecols = [f'column{i}' for i in range(1,51)]
this creates a list of strings with values column1, ..., column50
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nimantha |
| Solution 2 | Simon Hawe |
