As stated in the title, I have a function which should display an error message, but doesn't. I get an error:
Cannot set property 'textContent' of null
So basically, when a person clicks a check button, the input fields get a required "status". Once that happens, and error should appear underneath the input fields stating that they are required and should be filled out.
This does not happen (Cannot set property 'textContent' of null).
Any help would be welcome.
innerHTML of null error: pnameError.innerHTML = '';
textContent of null error: pnameError.textContent = 'You need to insert your name.';
JS
let pname = document.getElementById("popupfname");
let pnameError = document.querySelector("#popupfname + span#pf");
let pemail = document.getElementById("popupemail");
let pemailError = document.querySelector("#popupemail + span#pe");
var adverts = document.querySelector("input[name=advertsM]");
adverts.addEventListener('change', function() {
if (this.checked) {
console.log("CHECKED");
document.getElementById("popupfname").required = true;
document.getElementById("popupemail").required = true;
/* Prikaži error msg iz prve */
showNameError();
showEmailError();
} else {
console.log("NOT");
document.getElementById("popupfname").required = false;
document.getElementById("popupemail").required = false;
popfn();
popem();
}
});
function popfn (event) {
if (pname.validity.valid) {
pnameError.innerHTML = '';
pnameError.className = 'error'; //
} else {
showNameError();
}
};
function popem (event) {
if (pemail.validity.valid) {
pemailError.innerHTML = '';
pemailError.className = 'error';
} else {
showEmailError();
}
};
function showNameError() {
if (pname.validity.valueMissing) {
pnameError.textContent = 'You need to insert your name.';
} else if (pname.validity.typeMismatch) {
pnameError.textContent = 'Entered value must a name.';
} else if (pname.validity.tooShort) {
pnameError.textContent = 'Entered name must be atleast 3 characters long.';
}
pname.className = 'error active';
}
function showEmailError() {
if (pemail.validity.valueMissing) {
pemailError.textContent = 'You need to insert your e-mail address.';
} else if (pemail.validity.typeMismatch) {
pemailError.textContent = 'Entered value must be a valid e-mail address.';
} else if (pemail.validity.tooShort) {
pemailError.textContent = 'Entered e-mail address must be atleast 6 characters long.';
}
pemail.className = 'error active';
}
HTML
<form accept-charset="UTF-8" name="popupform" onsubmit="return false;" method="post" id="popupform">
<div id="adv-t"></div><br />
<label class="mlist">
<input type="checkbox" name="advertsM" id="advertsM" value="Yes">
<span id="adv-c"></span>
<br />
</label><br />
<input type="text" pattern="[A-Za-z][^0-9]{2,25}" name="popupfname" id="popupfname" placeholder="Janez"autocorrect="off" autocapitalize="off" /><br />
<span id="pf" class="error pfn" aria-live="polite"></span><br />
<input type="email" name="popupemail" id="popupemail" autocorrect="off" autocapitalize="off" maxlength="45" placeholder="moj#email.si"/><br />
<span id="pe" class="error pem" aria-live="polite"></span><br /><br />
<div id="small">
</div>
<hr style="margin-top: -6px;">
<button id="allow">
<span id="a"></span>
</button>
<button id="deny" onclick="deny()">
<span id="d"></span>
</button>
</form>
The problem is the next element to input is br, not a span
change
let pnameError = document.querySelector("#popupfname + span#pf")
...
let pemailError = document.querySelector("#popupemail + span#pe");
to
let pnameError = document.querySelector("#popupfname + br + span#pf")`
...
let pemailError = document.querySelector("#popupemail + br + span#pe");
Working example:
let pname = document.getElementById("popupfname");
let pnameError = document.querySelector("#popupfname + br + span#pf"); // <-- here ou had an error, because the next element to #popupfname is br, but not the span id="pf"
let pemail = document.getElementById("popupemail");
let pemailError = document.querySelector("#popupemail + br + span#pe"); // <-- here ou had an error, because the next element to #popupemail is br, but not the span id="pe"
var adverts = document.querySelector("input[name=advertsM]");
adverts.addEventListener( 'change', function() {
if(this.checked) {
console.log("CHECKED");
document.getElementById("popupfname").required = true;
document.getElementById("popupemail").required = true;
/* Prikaži error msg iz prve */
showNameError();
showEmailError();
} else {
console.log("NOT");
document.getElementById("popupfname").required = false;
document.getElementById("popupemail").required = false;
popfn();
popem();
}
});
function popfn (event) {
if (pname.validity.valid) {
pnameError.innerHTML = '';
pnameError.className = 'error'; //
} else {
showNameError();
}
};
function popem (event) {
if (pemail.validity.valid) {
pemailError.innerHTML = '';
pemailError.className = 'error';
} else {
showEmailError();
}
};
function showNameError() {
if(pname.validity.valueMissing){
pnameError.textContent = 'You need to insert your name.';
}else if(pname.validity.typeMismatch){
pnameError.textContent = 'Entered value must a name.';
}else if(pname.validity.tooShort){
pnameError.textContent = 'Entered name must be atleast 3 characters long.';
}
pname.className = 'error active';
}
function showEmailError() {
if(pemail.validity.valueMissing){
pemailError.textContent = 'You need to insert your e-mail address.';
}else if(pemail.validity.typeMismatch){
pemailError.textContent = 'Entered value must be a valid e-mail address.';
}else if(pemail.validity.tooShort){
pemailError.textContent = 'Entered e-mail address must be atleast 6 characters long.';
}
pemail.className = 'error active';
}
<form accept-charset="UTF-8" name="popupform" onsubmit="return false;" method="post" id="popupform">
<div id="adv-t"></div><br />
<label class="mlist">
<input type="checkbox" name="advertsM" id="advertsM" value="Yes">
<span id="adv-c"></span>
<br />
</label><br />
<input type="text" pattern="[A-Za-z][^0-9]{2,25}" name="popupfname" id="popupfname" placeholder="Janez"autocorrect="off" autocapitalize="off" /><br />
<span id="pf" class="error pfn" aria-live="polite"></span><br />
<input type="email" name="popupemail" id="popupemail" autocorrect="off" autocapitalize="off" maxlength="45" placeholder="moj#email.si"/><br />
<span id="pe" class="error pem" aria-live="polite"></span><br /><br />
<div id="small">
</div>
<hr style="margin-top: -6px;">
<button id="allow">
<span id="a"></span>
</button>
<button id="deny" onclick="deny()">
<span id="d"></span>
</button>
</form>
Related
I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.
You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
I want to get the return value of validatePassword() and validate() function outside its scope. Those values should be returned inside the function firstNextButton(). If both input fields are validated right, the button must be clickable, which means that the attribute disabled will be removed inside the element.
(function validationPassword() {
var inputPassWord = document.getElementById('inputpassword');
var passErrorMessage = document.getElementById('password-error');
function validatePassword() {
var inputPasswordValue = inputPassWord.value;
if(inputPasswordValue.length > 0) {
passErrorMessage.innerHTML = "Password correct";
} else {
passErrorMessage.innerHTML = "Password incorrect";
}
}
inputPassWord.onblur = function() {
firstNextButton();
}
})();
(function validationEmail() {
var emailInput = document.getElementById('email');
var emailError = document.getElementById('email-error');
var email = emailInput.value;
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
if(validateEmail(email)) {
emailError.innerHTML = 'Email is correct';
}
else {
emailError.innerHTML = 'mail not correct. Example: name#gmail.com';
}
return false;
}
emailInput.onblur = function() {
emailvalidate;
firstNextButton();
}
})();
function firstNextButton() {
var firstButton = document.getElementById('firstStepButton');
console.log('hello firstNextButton');
// if(validate() && validatePassword()) {
// console.log('hello world');
// firstButton.removeAttribute('disabled', '');
// } else {
// firstButton.setAttribute('disabled', '');
// }
}
<div class="form-block">
<div class="required-field">
<label class="control-label">Email Address</label>
<input name="email" id="email" class="form-control contact-input" type="email" placeholder="<?= $this->lang->line('application_email_address') ?>" required>
<span id="email-error"></span>
</div>
</div>
<div class="form-block">
<div class="required-field">
<label class="control-label">Password</label>
<input name="password" id="inputpassword" class="form-control contact-input" type="password" placeholder="<?= $this->lang->line('application_password') ?>" required>
<span id="password-error"></span>
</div>
</div>
<div>
<button class="btn btn-info btn-round nextBtn pull-right" id="firstStepButton" type="button">Sign Up</button>
</div>
To solely answer your question, you can return the functions you need like this :
var validationPassword = (function validationPassword() {
var inputPassWord = document.getElementById('inputpassword');
var passErrorMessage = document.getElementById('password-error');
function validatePassword() {
var inputPasswordValue = inputPassWord.value;
if (inputPasswordValue.length > 0) {
passErrorMessage.innerHTML = "Password correct";
} else {
passErrorMessage.innerHTML = "Password incorrect";
}
}
inputPassWord.onblur = function() {
firstNextButton();
}
return {
validatePassword: validatePassword
};
})();
var validationEmail = (function validationEmail() {
var emailInput = document.getElementById('email');
var emailError = document.getElementById('email-error');
var email = emailInput.value;
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
if (validateEmail(email)) {
emailError.innerHTML = 'Email is correct';
} else {
emailError.innerHTML = 'mail not correct. Example: name#gmail.com';
}
return false;
}
emailInput.onblur = function() {
validate();
firstNextButton();
}
return {
validate: validate
};
})();
function firstNextButton() {
var firstButton = document.getElementById('firstStepButton');
if(validationEmail.validate() && validationPassword.validatePassword()) {
console.log('hello world');
firstButton.removeAttribute('disabled', '');
} else {
firstButton.setAttribute('disabled', '');
}
}
<div class="form-block">
<div class="required-field">
<label class="control-label">Email Address</label>
<input name="email" id="email" class="form-control contact-input" type="email" placeholder="<?= $this->lang->line('application_email_address') ?>" required>
<span id="email-error"></span>
</div>
</div>
<div class="form-block">
<div class="required-field">
<label class="control-label">Password</label>
<input name="password" id="inputpassword" class="form-control contact-input" type="password" placeholder="<?= $this->lang->line('application_password') ?>" required>
<span id="password-error"></span>
</div>
</div>
<div>
<button class="btn btn-info btn-round nextBtn pull-right" id="firstStepButton" type="button">Sign Up</button>
</div>
Or refactor your code and take them outside the modules scopes.
As a side note, you forgot the parenthesis in emailInput.onblur function (and gave it the wrong name, too) :
emailInput.onblur = function() {
validate(); // <---- Here
firstNextButton();
}
Also, you don't call validePassword inside the onblur event, and you don't take the value of the input you're trying to validate. Add something like email = emailInput.value; inside the top of the validate function.
I'm search but i'm not 100% how you get this to resubmit, using new information, I've got all the errors up and showing as appropriate, but in terms of, how to hit the submit button again, and then it reassesses the form; how do i go about this? Any help would be appreciated.
html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>RATool</title>
<link rel="stylesheet" type="text/css" href="cfcss.css">
<script src="cf.js"></script>
</head>
<body>
<h1> Health Authority </h1>
<h2> Contact Form </h2>
<form>
<fieldset>
<label for="fname">First Name:</label>
<input name="fname" id="fname" class="formfield" type="text">
<span id="errfname" class="error">*This is required</span>
<span id="errfname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errfname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="sname">Surname:</label>
<input name="sname" id="sname" class="formfield" type="text">
<span id="errsname" class="error">*This is required</span>
<span id="errsname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errsname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="title">Title: </label>
<select name="title" id="title">
<option value="Please select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss.</option>
<option value="Master.">Master.</option>
</select>
<span id="errtitle" class="error">*This is required</span>
<br>
<br>
<br>
<label for="HANo">Health Authority Number:</label>
<input name="HANo" id="HANo" class="formfield"type="text">
<span id="errHANo" class="error">*This is required</span>
<span id="errHANo2" class="error">*This must be in format ZHA123456 (ZHA followed by 6 numbers)</span>
<br>
<br>
<label for="email">Email:</label>
<input name="email" id="email" class="formfield"type="text">
<span id="erremail" class="error">*This is required</span>
<span id="erremail2" class="error">*Please enter a valid email</span>
<br>
<br>
<br>
<label for="telno">Telephone Number:</label>
<input name="telno" id="telno" class="formfield" type="text">
<span id="errtelno" class="error">* If a telephone number is entered, then it should contain only numbers, not
letters, or other disallowed characters. A valid Zedland telephone number has
11 digits (no spaces)</span>
<span id="errtelno1" class="error">*This must just be numbers</span>
<br>
<button onclick="checkForm()">Submit</button>
</fieldset>
</form>
</body>
</html>
javascript
function checkForm(){
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length > 1) {
checkFName();
e.preventDefault();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length > 1) {
checkSName();
e.preventDefault();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value.length > 0) {
if (checkHANo());
e.preventDefault();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
e.preventDefault();
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
e.preventDefault();
}
}
function checkEmail(){
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("erremail2").style.display="inline";
document.getElementById("erremail2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkHANo(){
var HANo = document.getElementById("HANo");
var hanoRegEx = /[ZHA]\d{6}/;
if (!hanoRegEx.test(HANo.value)) {
document.getElementById("errHANo2").style.display = "inline";
document.getElementById("errHANo2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkFName(){
var first = document.getElementById("fname");
var firstRegEx = /^[a-zA-Z-]{2,40}$/;
if (!firstRegEx.test(first.value)){
document.getElementById("errfname2").style.display = "inline";
document.getElementById("errfname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkSName(){
var sec = document.getElementById("sname");
var secRegEx = /^[a-zA-Z-]{2,40}$/;
if (!secRegEx.test(sec.value)){
document.getElementById("errsname2").style.display = "inline";
document.getElementById("errsname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
Your error messages are displaying by default. To hide those add the CSS class below:
.error{ display:none; }
Add this piece of code at the beginning of checkForm() to re-hide the message when error is corrected. Eg:
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
Instead of calling the formCheck() function on onclick of the button, call it onsubmit of the form with a return. Like
<form method="post" action="yourpage" onsubmit="return checkForm()">
To show all errors, declare a variable with default value as true like var isValid=true; just above/below the for loop
Eg:
function checkForm(){
var isValid = true;
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length > 1) {
isValid = checkFName();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length > 1) {
isValid = checkSName();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value.length > 0) {
isValid = checkHANo();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
isValid = false;
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
isValid = false;
}
return isValid;
}
NOTE: You have to return false from other functions such as checkEmail(),checkHANo() also if there is error. It seems you are returning only true. And remove all e.preventDefault()
That's it
I have a submit form that users are using to register:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" name="form" onSubmit="return validate(this);">
<div class="form-group">
<input type="text" id="name" name="name" class="inputs" /><br />
<input type="text" id="email" name="email" class="inputs" /><br />
<input type="password" id="password" name="password" class="inputs" />
</div>
<input type="submit" class="btn1" name="register" value="Register" />
</form>
The JS code is checking if the data is entered correctly. If the user enters incorrect date the JS code is showing a message. Now I want to show a message when the data is entered correctly. I tried to add a row like if (errors.length < 0) but this didn't work. The JS code sends me the message for the "correct input" and the message "Dont use symbols...\n".
How can I make this working?
Here is my JS code:
<script type="text/javascript">
var ck_name = /[A-Za-z0-9. ]{3,25}$/;
var ck_email = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
function validate(form)
{
var name = form.name.value;
var email = form.email.value;
var password = form.password.value;
var errors = [];
if (!ck_name.test(name))
{
errors[errors.length] = "Name error! .";
}
if (!ck_email.test(email))
{
errors[errors.length] = "Email error! .";
}
if (!ck_password.test(password))
{
errors[errors.length] = "Password error!";
}
if (errors.length > 0)
{
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors)
{
var msg = "Dont use symbols...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
Errors.length never won't be minor of 0. You must use equal (==). This works! :-)
UPDATE
if (errors.length == 0) {
alert('Correct input');
}
That would be before the return true statement and after the if (errors.length > 0).
Im trying to have a blur event for when username and password are to short it says username/password must be x long.
For some reason it only works on my username and I have no clue why
HTML
<body>
<div id="page">
<h1>List King</h1>
<h2>New Account</h2>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" />
<div id="feedback"></div>
<label for="password1">Create a password: </label>
<input type="password" id="password"/>
<div id="feedback"></div>
<input type="submit" value="sign up" />
</form>
</div>
<script src="event-listener.js"></script>
</body>
javascript
function checkUsername() {
var elMsg = document.getElementById('feedback');
if (this.value.length < 5) {
elMsg.textContent = 'Username must be 5 characters or more';
} else {
elMsg.textContent = '';
}
}
var elUsername = document.getElementById('username');
elUsername.addEventListener('blur', checkUsername, false);
function checkPassword() {
var elMsg = document.getElementId('feedback');
if (this.value.length < 6){
elMsg.textContent = 'Password must be 6 characters or more';
} else {
elMsg.textContent = ' ';
}
}
var elPassword = doucment.getElementById('password');
elPassword.addEventListener('blur', checkPassword, false);
Created a plunkr example here< https://plnkr.co/edit/MBkFQSEjbKIAFPDOFUTW?p=preview >. You have few spelling mistakes in your code and used the same id to show the message. I used html5 tags for blur event instead of event listeners.
function checkUsername() {
var usernameLength=document.getElementById('username').value.length;
var elMsg = document.getElementById('feedback1');
if (usernameLength < 5) {
elMsg.textContent = 'Username must be 5 characters or more';
} else {
elMsg.textContent = 'good';
}
}
function checkPassword() {
var elPassword = document.getElementById('password');
var elMsg = document.getElementById('feedback2');
if (elPassword.value.length < 6){
elMsg.textContent = 'Password must be 6 characters or more';
} else {
elMsg.textContent = ' ';
}
}
</head>
<body>
<div id="page">
<h1>List King</h1>
<h2>New Account</h2>
<form method="post" action="http://www.example.org/register">
<label for="username">Create a username: </label>
<input type="text" id="username" />
<div id="feedback"></div>
<label for="password1">Create a password: </label>
<input type="password" id="password"/> <div id="feedback1"></div>
<input type="submit" value="sign up" />
</form>
</div>
<script src="event-listener.js"></script>
</body>
</html>
function checkUsername() { // Declare function
var elMsg = document.getElementById('feedback'); // Get feedback element
if (this.value.length < 5) { // If username too short
elMsg.textContent = 'Username must be 5 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear msg
}
}
var elUsername = document.getElementById('username'); // Get username input
// When it loses focus call checkUsername()
elUsername.addEventListener('blur', checkUsername, false);
function CheckPassword() { // Declare function
var elMsg = document.getElementById('feedback1'); // Get feedback element
if (this.value.length < 6) { // If username too short
elMsg.textContent = 'Password must be 6 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear msg
}
}var elPassword = document.getElementById('password'); // Get username input
elPassword.addEventListener('blur', CheckPassword, false);