Home > Back-end >  Error message displayed even with valid inputs
Error message displayed even with valid inputs

Time:06-07

I was trying to validate my HTML form with the help of Javascript, but the error messages get displayed even after providing valid inputs. If I add 'preventDefault()', the error messages get displayed only with invalid inputs but the form gets submitted anyway. My code-

HTML

<form id="form" novalidate onsubmit="return validate()">

<label for="firstName">Enter your first name</label><br>
<input type="text" id="firstName" name="firstName" required><br>
<span role="alert" id="nameError" aria-hidden="true"> Please enter a valid name </span>
<label for="lastName">Enter your last name here</label><br>
<input type="text" id="lastName" name="lastName" required><br>
<span role="alert" id="lastNameError" aria-hidden="true"> Please enter a valid name </span> 
/*other elements in the form */

Javascript for error messages

const firstNameField = document.getElementById("firstName");
const lastNameField = document.getElementById("lastName");

let valid = true;

if (firstNameField.getAttribute(length)<3
|| firstNameField.getAttribute(pattern)!="[A-Za-z ]"
|| lastNameField.getAttribute(length)<3
|| lastNameField.getAttribute(pattern)!="[A-Za-z ]")
 {
const nameError = document.getElementById("nameError");
nameError.classList.add("visible");
firstNameField.classList.add("invalid");
nameError.setAttribute('aria-hidden', false);
nameError.setAttribute('aria-invalid', true);

const lastNameError = document.getElementById("lastNameError");
lastNameError.classList.add("visible");
lastNameField.classList.add("invalid");
lastNameError.setAttribute('aria-hidden', false);
lastNameError.setAttribute('aria-invalid', true);


valid = false;

}

return valid;
}

CSS for the error messages

#nameError, #lastNameError{
display: none;
font-size: 0.8em;
color: red;
}

#nameError.visible, #lastNameError.visible{
  display: block;
}

input.invalid {
 border-color: red;
}

I'm new to Javascript so any suggestions would be helpful for me

CodePudding user response:

In addition to preventDefault() also add, stopPropagation() to prevent the submit event from bubbling up to the form and submitting it.

CodePudding user response:

It seems like you are missing the closing bracket on your if condition.

Also try to make a runnable example with snippet this description on stackoverflow should help

CodePudding user response:

You can do something like this in js:

document.getElementById('form').addEventListener('submit', function(e) {  
  e.preventDefault();
  console.log('run validation here, return true or false to submit');
}

CodePudding user response:

You can try this way

`<form name="" action="/action_page.php" onsubmit="return validateForm()" method="post">

Name:

`
`function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  if (x == "") {
   alert("Name must be filld out");
   return fales;
 }
}`
  • Related