Reputation: 17
I have created five input fields and a submit button to validate that fields but somehow it is not validated on submit.
In my JS I print the error dynamically. I have debugged by code and I get the proper values and errors, but it doesn't displays dynamically.
function seterror(id, error) {
// set error
var element = document.getElementById(id);
debugger;
console.log(element);
element.getElementsByClassName('ferror')[0].innerHTML = error;
}
function validateForm(e) {
e.preventDefault();
var returnval = true;
var name = document.forms['myForm']['fname'].value;
if (name.length < 5) {
seterror("uname", "abc");
returnval = false;
}
return returnval;
}
.ferror {
color: red;
}
<h1>Form Validation Demo</h1>
<form onsubmit="return validateForm()" name="myForm">
Name*: <input type="text" id="uname" name="fname"><b><span class="ferror"></span></b><br> Password*: <input type="password" id="pass" name="fpass"><b><span class="ferror"></span></b><br> Confirm Password*: <input type="password" id="cpassword" name="fcpass"><b><span class="ferror"></span></b> <br> Email*: <input type="email" id="uemail" name="femail"><b><span class="ferror"></span></b> <br> Phone*:
<input type="phone" id="uphone" name="fphone"><b><span class="ferror"></span></b> <br>
<input type="submit" class="btn" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Upvotes: 0
Views: 4399
Reputation: 206028
Given all the comments under the question, here's my suggestion for a more flexible remake:
<label>
as wrapper<span>
error elements - create them using JSerrors
array to store all the errors during each part of the validationerrors
Array has items in it (meaning something is invalid) - in that case use Event.preventDefault()
to prevent the form being submitted.// Utility functions:
const EL = (sel, parent) => (parent || document).querySelector(sel);
const ELS = (sel, parent) => (parent || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Form validation script:
const EL_form = EL("#myForm");
const validateForm = (evt) => {
// Remove old errors
ELS(".ferror", EL_form).forEach(el => el.remove());
// Prepare an array to hold your errors
const errors = [];
// Get the desired fields:
const EL_fname = EL('[name="fname"]', EL_form);
const EL_fpass = EL('[name="fpass"]', EL_form);
const EL_fcpass = EL('[name="fcpass"]', EL_form);
const EL_femail = EL('[name="femail"]', EL_form);
const EL_fphone = EL('[name="fphone"]', EL_form);
// Validation and errors:
if (EL_fname.value.trim().length <= 4) {
errors.push({name: "fname", text: "Name is too short (min 4 chars)"});
}
if (EL_fpass.value.trim().length <= 8) {
errors.push({name: "fpass", text: "Password is too short (min 8 chars)"});
}
if (EL_fpass.value !== EL_fcpass.value) {
errors.push({name: "fcpass", text: "Passwords do not match"});
}
if (!/^.+@.+\./.test(EL_femail.value)) {
errors.push({name: "femail", text: "Invalid Email address"});
}
if (EL_fphone.value.trim().replace(/\D/g, "").length <= 6) {
errors.push({name: "fphone", text: "Invalid telephone number"});
}
// Show errors:
errors.forEach(err => {
const EL_error = ELNew("span", {
className: "ferror",
textContent: err.text,
});
EL(`[name="${err.name}"]`, EL_form).closest("label").append(EL_error);
});
// Prevent Form subnit on any error
if (errors.length) {
evt.preventDefault();
}
};
EL_form.addEventListener("submit", validateForm);
form label {
display: block;
}
.ferror {
color: red;
font-weight: 700;
}
<form id="myForm">
<label>Name: <input name="fname" type="text"></label>
<label>Password: <input name="fpass" type="password"></label>
<label>Confirm Password: <input name="fcpass" type="password"></label>
<label>Email: <input name="femail" type="email"></label>
<label>Phone: <input name="fphone" type="phone"></label>
<br>
<input type="submit" class="btn" value="Submit">
</form>
Upvotes: 1