Form validation onblur() doesn't work - javascript

I have this javascript code (the function SHA-1 is located in an external file):
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onblur = function doSomething() {
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}
and this in html:
<form name="form" method="post" action="change_pass.php">
<div class="row">
<div class="col1">write your password:<span class="required">*</span></div>
<div class="col2">
<input type="password" name="original_pass" id="oriPass" />
</div>
</div>
</form>
For some reason, every time I test it I get the same output: "valid password", no matter if the field is empty, valid or invalid.
What am I doing wrong here?

move the var user_pass... and var hashed_pass... code inside the onblur function. Now the are assigned only onload and will never change. Also it might be better to use onchange instead of onblur.
window.onload = validatePass;
function validatePass() {
var el = document.getElementById("oriPass");
var span = document.createElement("span");
el.parentNode.appendChild(span);
el.onchange = function doSomething() {
var user_pass = el.value;
var hashed_pass = SHA1(user_pass);
if(user_pass == null || user_pass == "") {
span.setAttribute('class','required');
span.innerHTML="this is a required field";
}
else {
if(hashed_pass != '7c4a8d09ca3762af61e59520943dc26494f8941b') {
span.setAttribute('class','required');
span.innerHTML="wrong password";
}
else {
span.setAttribute('class','required_ok');
span.innerHTML="valid password";
}
}
}
}

You are setting the variable for password only on load. It never changes after that. You need to set it inside the onblur function.

Related

I have a problem with form validation in JS DOM

When i click a field and pass another, span tag is getting red color. Then i press the submit button it is showing alert message. But when i turn to red span and fill in the field and press submit button it is showing success even if other fields are blank.
const regForm = document.getElementById('regForm');
var validObjects = document.querySelectorAll('[customValidate]');
validObjects.forEach(function(element) {
element.addEventListener('blur', function() {
var emoji = element.previousElementSibling;
var label = emoji.previousElementSibling;
if (!element.value) {
emoji.className = "far fa-frown float-right text-danger";
var span = document.createElement("span");
span.innerHTML = " * Required";
span.style.color = "red";
if (!label.getElementsByTagName("span")[0])
label.appendChild(span);
isValid = false;
} else {
emoji.className = "far fa-smile float-right text-success";
var span = label.getElementsByTagName("span")[0];
if (span)
label.removeChild(span);
isValid = true;
}
});
});
regForm.addEventListener('submit', function(event) {
event.preventDefault();
var isValid = true;
validObjects.forEach(function(element) {
isValid = element.value ? true : false;
})
if (!isValid) {
alert("empty!");
} else {
alert("success!");
}
});
JSFiddle :https://jsfiddle.net/roop06/cjmdabrf/
because isValid is only going to be equal to the last item in the forEach
validObjects.forEach(function(element) {
isValid = element.value ? true : false; // replaces false with true on last iteration
})
If you want to use a forEach you would want to code it like this so it does not overwrite isValid. It uses its previous state.
var isValid = true;
validObjects.forEach(function(element) {
isValid = element.value ? isValid : false;
})
But if you are not doing anything else in the forEach loop, there is a better option. That option is to use every which will exit when it gets to false.
var isValid = validObjects.every(function (element) {
return element.value.length
})
var form = document.querySelector('form');
var validObjects = Array.from(document.querySelectorAll('[customValidate]'));
form.addEventListener("submit", function (e) {
var isValid = validObjects.every(function (element) {
return element.value.length
})
return isValid
})
<form>
<input customValidate>
<input customValidate>
<input customValidate>
<button>submit</button>
</form>
Or you can just use the built in HTML5 validation using required and let the browser do it for you.
<form>
<input customValidate required>
<input customValidate required>
<input customValidate required>
<button>submit</button>
</form>
Try this
JSFiddle
validObjects.forEach(function(element) {
if(!(element.value)){
isValid = false;
}
})
The problem you have is that if the last field is valid then the isValid flag will always be true. One way to get around this is to stop setting the flag once you have determined that there is an invalid field:
validObjects.forEach(function (element) {
if (isValid) {
isValid = element.value ? true : false;
}
});

JQuery Form Validation Does Nothing

This code isn't doing anything when I submit the form. What am I doing wrong? In the HTML, an error message is shown or hidden based on a class.
I hope you can help me figure out this problem. Thanks in advance.
$(document).ready(function() {
function validateForm() {
var first_name = $("#first_name").value;
var last_name = $("#last_name").value;
var phone = $("#phone").value;
var email = $("#email").value;
var code = $("#vali_code").value;
var ssn = $("#ssn").value;
var income = $("#nm_income").value;
var error = $(this).find("span.error_txt").removeClass(".hidden").addClass(".show");
var emailReg = /^([w-.]+#([w-]+.)+[w-]{2,4})?$/;
if (first_name === "") {
error;
}
if (last_name === "") {
error;
}
if (email === "" || email !== emailReg) {
error;
}
if (phone === "" || phone < 9) {
error;
}
if (ssn === "" || ssn > 4) {
error;
}
if (income === "") {
error;
}
if (code === "") {
error;
}
return true;
}
});
If you call the function in inline event onsubmit you should add return keyword to the function call in your form inline event like :
<form onsubmit='return validateForm()'>
But I think the main problem comes from the .value in your code it should be replaced by .val() since the value isn't an attribute of jQuery objects.
My suggestion is to attach the submit event in the JS code like the snippet below.
NOTE: The argument passed toremoveClass() and addClass() methods shouldn't contains dot . at the start.
$(function() {
$('form').on('submit', validateForm);
})
function validateForm() {
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
$(this).find("span.error_txt").removeClass("hidden").addClass("show");
if (first_name === "") {
return false;
}
if (last_name === "") {
return false;
}
alert('Form will be submited.');
return true;
}
.hidden {
display: none;
}
.show {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id='first_name'><br>
<input id='last_name'><br>
<button>Submit</button>
<span class="error_txt hidden">Error occurred check you form fields again.</span>
</form>
You need to return false in case the form is invalid, otherwise it will be submitted.

jQuery form validation ( if == "" do this) only works on first input

I have a form which I'm using jQuery to validate that the inputs aren't empty. (I'm using bootstrap too)
<form action="" method="post">
<div id="name_input" class="form-group">
<input id="name" type="text" name="name" placeholder="Name">
<span class="glyphicon glyphicon-remove form-control-feedback name_span></span>
</div>
<div id="email_input" class="form-group">
<input id="email" type="email" name="email" placeholder="Email">
<span class="glyphicon glyphicon-remove form-control-feedback email_span></span>
</div>
<input type="submit" name="submit" value="save">
</form>
with jQuery
$(document).ready(function() {
$('.form-control-feedback').hide();
$(".submit").click(function() {
var name = $("#name").val();
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
return false;
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
return false;
}
});
});
when I use this code and both inputs are empty, the classes "has-error" and "has-feedback" only append to the first input.
if the first input is filled in and the second is empty the classes adds to the second one, and if I empty the first one too that one also get the classes.
but if I do the other way around, so the first is empty first and the secound input is empty after, the classes still only add to the first one.
Also when I fill one of them in, I want to removeClass but I can't do that with:
} else {
$("#name_input").removeClass("has-error has-feedback");
$(".name_span").hide();
}
since that will submit the form and obvious I can't add return false; since that will prevent the form to process even if it's filled in... Any suggestions on these?
A return statement immediately stops executing a function. So this code here
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
return false;
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
return false;
}
Says that if name == "" , don't even evaluate the email. Instead, you may want to use a flag to see if any errors occurred.
var dataIsValid = true;
var name = $("#name").val();
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
dataIsValid = false;
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
dataIsValid = false;
}
return dataIsValid;
As #imvain2 pointed out, you'll also want to remove the error classes. Otherwise, as soon as you get an error once, it will always look like they have an error.
var dataIsValid = true;
var name = $("#name").val();
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
dataIsValid = false;
} else { // Valid, remove the error classes
$("#name_input").removeClass("has-error has-feedback");
$(".name_span").hide();
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
dataIsValid = false;
} else { // Valid, remove the error classes
$("#email_input").removeClass("has-error has-feedback");
$(".email_span").hide();
}
return dataIsValid;
You are returning on the first error. If you want to list through each you need to remove the individual return statements.
$(document).ready(function() {
$('.form-control-feedback').hide();
$(".submit").click(function() {
var name = $("#name").val(),
errorMsg = [];
if (name == "") {
$("#name_input").addClass("has-error has-feedback");
$(".name_span").show();
errorMsg.push('Invalid Name');
}
var email = $("#email").val();
if (email == "") {
$("#email_input").addClass("has-error has-feedback");
$(".email_span").show();
errorMsg.push('Invalid Email');
}
if (errorMsg.length > 0 ){
// alert('Errors:\n' + errMsg.join('\n'));
return false;
}
});
});

Return false does not prevent form submission

I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}

JavaScript form validation on server/local

I'm using JavaScript form validation for the entry form for a contest I'm running. It's inline CSS so that if certain conditions aren't met, it displays, in red, messages that say "please enter your email address" or "that doesn't look like a valid email address" etc.
The script, which sits at the top of the file, looks like this:
<script>
function checkForm() {
name = document.getElementById("name").value;
email = document.getElementById("email").value;
terms = document.getElementById("terms").value;
if (name == "") {
hideAllErrors();
document.getElementById("nameError").style.display = "inline";
document.getElementById("name").select();
document.getElementById("name").focus();
return false;
} else if (email == "") {
hideAllErrors();
document.getElementById("emailError").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if (!check_email(document.getElementById("email").value)) {
hideAllErrors();
document.getElementById("emailError2").style.display = "inline";
document.getElementById("email").select();
document.getElementById("email").focus();
return false;
}
else if (!document.form1.terms.checked){
hideAllErrors();
document.getElementById("termsError").style.display = "inline";
document.getElementById("terms").select();
document.getElementById("terms").focus();
return false;
}
return true;
}
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.#-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(#.*#)|(\.\.)|(^\.)|(^#)|(#$)|(\.$)|(#\.)/;
re_two = /^.+\#(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);
}
}
}
function hideAllErrors() {
document.getElementById("nameError").style.display = "none"
document.getElementById("emailError").style.display = "none"
document.getElementById("commentError").style.display = "none"
document.getElementById("termsError").style.display = "none"
}
The email and name validation work just fine, the part of the form that won't work looks like this:
<form onSubmit="return checkForm();" method="get" action="sweepstakes-results.php"
<input type=checkbox name=terms id=terms ><br></p>
<div class=error id=termsError>Required: Please check the checkbox<br></div>
<p><input type=submit value=Send style="margin-left: 50px"> </p>
</form>
The "terms and conditions" checkbox only works if the file is on my local machine, when I upload it, it just lets me submit the form even if it's not checked. Isn't JavaScript run on the browser? How could the location of the file make a difference?
Your form doesn't have a name, so the following code won't work:
else if (!document.form1.terms.checked){
Since you're already retrieving the DOM object of the checkout, do the following. Change the line:
terms = document.getElementById("terms").value;
to:
terms = document.getElementById("terms");
And the replace that else if code with:
else if (!terms.checked){

Categories