inherit function that is inside scope to another function - javascript

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.

Related

validity API to validate a form

I'm trying to validate a form with validity API, but have some issues (2 to be precise) . One for valueMissing where the textContent couldn't be displayed and the second when submitting the form (all fiels are corect then) : nothing happen, I can't see the console.log. Here is the code
html
const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
// function valid() : allow sending form after checking it
function valid(e) {
e.preventDefault();
let isFormOk = true;
let fname = document.getElementById('fname');
let missFname = document.getElementById('fname_missing');
let firstNameValue = document.getElementById('fname').value;
let email = document.getElementById('email');
let missEmail = document.getElementById('email_missing');
let emailValue = document.getElementById('email').value;
let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'\s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
let emailValid = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//Validate the firstname :
if (fname.validity.valueMissing) { //if the field is empty
missFname.textContent = 'Enter your firstname please!';
missFname.style.color = 'red';
isFormOk = false;
}
if (fnameValid.test(fname.value) == false) { // if the format is incorrect
missFname.textContent = 'Incorrect format';
missFname.style.color = 'black';
isFormOk = false;
}
//Validate the email :
if (email.validity.valueMissing) {
missEmail.textContent = 'Email missing';
missEmail.style.color = 'red';
isFormOk = false;
}
if (emailValid.test(email.value) == false) {
missEmail.textContent = 'Incorrect format';
missEmail.style.color = 'black';
isFormOk = false;
}
if (isFormOk) {
let contact = {
firstNameValue,
emailValue
};
console.log(contact);
}
<form novalidate id="myForm">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" required>
<span id="fname_missing"></span>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" required>
<span id="email_missing" class="errorMail" aria-live="polite"></span>
</div>
<div class="form-group">
<button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>
const formValid = document.getElementById('myButton');
formValid.addEventListener('click', valid);
// function valid() : allow sending form after checking it
function valid(e) {
e.preventDefault();
let isFormOk = true;
let fname = document.getElementById('fname');
let missFname = document.getElementById('fname_missing');
let firstNameValue = document.getElementById('fname').value;
let email = document.getElementById('email');
let missEmail = document.getElementById('email_missing');
let emailValue = document.getElementById('email').value;
let fnameValid = /^[a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+([-'\s][a-zA-ZéèîïÉÈÎÏ][a-zéèêàçîï]+)?$/;
let emailValid = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//Validate the firstname :
if (fname.validity.valueMissing) { //if the field is empty
missFname.textContent = 'Enter your firstname please!';
missFname.style.color = 'red';
isFormOk = false;
}
if (fnameValid.test(fname.value) == false) { // if the format is incorrect
missFname.textContent = 'Incorrect format';
missFname.style.color = 'black';
isFormOk = false;
}
//Validate the email :
if (email.validity.valueMissing) {
missEmail.textContent = 'Email missing';
missEmail.style.color = 'red';
isFormOk = false;
}
if (emailValid.test(email.value) == false) {
missEmail.textContent = 'Incorrect format';
missEmail.style.color = 'black';
isFormOk = false;
}
if (isFormOk) {
let contact = {
firstNameValue,
emailValue
};
missEmail.style.display = 'none';
missFname.style.display = 'none';
console.log(contact);
}
return isFormOk;
}
<form novalidate id="myForm">
<div class="form-group">
<input type="text" class="form-control" name="fname" id="fname" required>
<span id="fname_missing"></span>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" required>
<span id="email_missing" class="errorMail" aria-live="polite"></span>
</div>
<div class="form-group">
<button id="myButton" name="myButton" type="submit">Confirm</button>
</div>
</form>
There is a curly brace missing in javascript function. Check this if it answers your question.

function which should display an error message does not display it

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>

validating using onblur and onsubmit

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>

Password blur event not showing

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);

.focus() after submit incorrect infos to a form, doesn't work

I have an easy form. When i submit the form with incorrect informations, the error message appear but i would that the first incorrect input is highlight with focus.
I think how i use .focus() is right but it might doesn't fit with the rest of the function.
Here my code:
<form name="login-registration" onSubmit="return validateForm()" method="post" action="" novalidate >
<div class="span-4">
<label>Email</label>
<label>Your password</label>
<label>Repeat password</label>
<label> <input class="inline check" type="checkbox" id="policy" name="policy" value="policy" /> I agree</label>
</div>
<div class="span-4">
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_POST['emailinput']); ?>"/>
<input type="password" name="pswinput" id="pswinput" value=""/>
<input type="password" name="pswrepeatinput" id="pswrepeatinput" value="" onblur="isValidPswRep()"/>
<input type="submit" name="submit" value="Login" />
</div>
<div class="span-4">
<p id="emptyEmail" class="hidden">Email field is required</p>
<p id="invalidEmail" class="hidden">Email you insert is invalid!</p>
<p id="pswMinMax" class="hidden">Password should be from 4 to 8 caracters</p>
<p id="pswLettNum" class="hidden">Password should be letters and numbers. No special caracters are allow</p>
<p id="pswR" class="hidden">Your passwords is different</p>
<p id="checkN" class="hidden">You must agree to our term</p>
</div>
</form>
And here the script:
function validateForm(){
var email = document.getElementById("emailinput").value;
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
var check = document.getElementById("policy");
if (isValidEmail(email)){
if(isValidPsw(psw,4,8)){
if(isValidPswRep(pswrep)){
if(isValidCheckbox(check)){
return true;
}
}
}
}
return false;
}
function isValidEmail(email) {
var validCharacters = /^\w+#\w+\.\w+$/;
if(email == ""){
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "error";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return false;
email.focus();
} else if(!validCharacters.test(email)) {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "error";
return false;
email.focus();
} else {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return true;
}
}
function isValidPsw(psw, minLen, maxLen) {
var lengthPsw = psw.length;
var lettNum = /^[0-9a-zA-Z]+$/;
if(lengthPsw == 0 || lengthPsw <= minLen || lengthPsw > maxLen){
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return false;
psw.focus();
} else if(!lettNum.test(psw)){
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "error";
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
return false;
psw.focus();
} else {
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "hidden";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return true;
}
}
function isValidPswRep(pswrep){
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
if(pswrep != psw){
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "error";
return false;
pswrep.focus();
}
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "hidden";
return true;
}
function isValidCheckbox(check){
if (!check.checked){
var checkErr = document.getElementById("checkN");
checkErr.className = "error";
return false;
check.focus();
}
var checkErr = document.getElementById("checkN");
checkErr.className = "hidden";
return true;
}

Categories