Validate a form only if every input is empty - javascript

Well, the question's pretty self-explanatory. I've been looking for a while and haven't found a proper way to do this kind of validation.
All I need to do is to run an error message if all the inputs are empty. If one of them is filled, then I don't need to stop the form from submitting.
I thought something like:
function checkForm() {
$('input').each(function(){
if( $(this).val() == "" ){
return false;
}
});
});
But this will stop my form if there's, at least, one input without data.
Any ideas? Thanks in advance.

Reverse your logic. I.e. return true if any input has a value, otherwise return false:
function checkForm() {
$('input').each(function() {
if ($(this).val() !== '') {
return true;
}
});
return false;
};

Reverse your logic since you want to check if the value is non-empty for one input field.
Also you probably want to return from your actual function and not from the callback which has no effect.
function checkForm() {
let bool = false;
$('input').each(function(){
if( $(this).val() !== '' ){
bool = true;
}
});
console.log(bool);
return bool;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<button onclick="checkForm()">check</button>

Related

Check if all inputs are empty

I have multiple inputs on my page, when any them are filled, an "info div" appears on the side;
Now if all the inputs are manually cleared (on keyup), I need to hide that "info div".
How can I check (on keyup) that all of the inputs are empty at the same time?
Cheers
Loop through all the inputs, and if you get to a non-empty one you know they're not all empty. If you complete your loop without finding one, then they are all empty.
function isEveryInputEmpty() {
var allEmpty = true;
$(':input').each(function() {
if ($(this).val() !== '') {
allEmpty = false;
return false; // we've found a non-empty one, so stop iterating
}
});
return allEmpty;
}
You might want to 'trim' the input value before comparing (if you want to treat an input with just whitespace in it as empty). You also might want to be more specific about which inputs you're checking.
Simple solution (ES6) Without jQuery
html
<div class="container">
<input id="input1" />
<input id="input2" />
<input id="input3" />
</div>
JS
document.getElementById('btnCheckEmpty').addEventListener('click', () => {
if (isEveryInputEmpty())
alert('empty');
else
alert('not empty');
});
const isEveryInputEmpty = () => {
var inputs = document.querySelectorAll('.container input');
for (const input of inputs)
if (input.value !== '') return false;
return true;
}
Online Demo

Weirdest repeat call of function ever

I made a questionnaire form that has a problem with the validation. There are several validating functions, that are called when clicking the submit button. But the first validating function is then called twice. To show the problem, I made a bare bones version that has the same problem. This is the whole source code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Demo Double Call</title>
</head>
<body>
<form name="upssForm" action="submit.php" method="POST" onsubmit="return validateForm()">
A1 <input type="radio" name="A" value="1">
A2 <input type="radio" name="A" value="2"><br>
B1 <input type="radio" name="B" value="1">
B2 <input type="radio" name="B" value="2"><br>
<button type="button" onclick="validateForm()">Validate and submit button</button><br>
<input type="submit" value="Validate and submit input">
</form>
<script>
function checkA() {
var radioA = upssForm.elements['A'];
if (radioA[0].checked == false) {
alert('A1 not checked');
return false;
}
else return true;
}
function checkB() {
var radioB = upssForm.elements['B'];
if (radioB[0].checked == false) {
alert('B1 not checked');
return false;
}
else return true;
}
function validateForm() {
checkA();
checkB();
if ((checkA() == false) || (checkB() == false))
return false;
else
upssForm.submit();
// return true; /* doesn't work either with the submit input */
}
</script>
</body>
</html>
Just click the submit button or the submit input, and see that the alert 'A1 not checked' comes up twice, the second time after the function checkB() is executed. What is causing this, and how do I solve it?
You are calling checkA() twice, once at the beginning of validateForm() and once in the if() statement.
Store the result in a variable, and then check that in the if() statement:
var aResult = checkA();
if(aResult == false) {
}
The answer WildCrustacean gave indeed solved the problem. For the record and future reference, I'll just give the whole function how it should be:
function validateForm() {
var aResult = checkA();
var bResult = checkB();
if ((aResult == false) || (bResult == false))
return false;
else
upssForm.submit();
}
Thanks, bro!
WildCrustacean's answer is correct, so I've edited mine down. Just FYI, you might want to refactor your if statements. For example, if (foo == false) is the same as if (!foo) (although, interestingly, if (foo === false) is not). So, incorporating WildCrustacean's answer and taking out some redundant code:
function checkA() {
var radioA = upssForm.elements['A'];
if (!radioA[0].checked) {
alert('A1 not checked');
}
return radioA[0].checked;
}
//function checkB() { ...
function validateForm() {
var a = checkA();
var b = checkB();
if (a && b) {
upssForm.submit();
}
return false;
}
It's okay that validateForm always returns false, because the only time that affects anything is when the user clicks the input (not the button) while the form is invalid.
Demo: http://jsfiddle.net/5GA5F/2/
In fact, if you don't mind odd-looking code, you can take advantage of Boolean short-circuiting to shrink the code even more:
function checkA() {
var radioA = upssForm.elements['A'];
return radioA[0].checked || alert('A1 not checked');
}
function checkB() {
var radioB = upssForm.elements['B'];
return radioB[0].checked || alert('B1 not checked');
}
function validateForm() {
var a = checkA(),
b = checkB();
return a && b && upssForm.submit();
}
Demo: http://jsfiddle.net/5GA5F/3/
Here's another way to do it:
function validateForm() {
if ((result = (checkA() && checkB()))){
upssForm.submit();
}
return result;
}
This way, your function always returns information on whether it succeeds or not. Another thing to notice here: in JavaScript, assignment statements return the value of the assignment. We didn't have to assign the result value separately because we could call it in the if condition.
One thing to keep in mind: checkB() will only run if checkA() succeeds. If you need them both to execute, assign their values to a variable and then check those variables.

Form Validation not working on all fields but only the first

When i post form only the title validation is working, the other two fields are not validated.
HTML
<form name="qaform" class="nice" method="POST" onsubmit="validateForm()" action="/ask/ask-question/">
<input type="hidden" id="id_selected_tags" name="tags">
<p>
<label for="id_title" class="inline-block">Title</label>
<input type="text" class="input-text inline-block" id="id_title" name="question_title">
</p>
<span id="error_title"></span>
<textarea id="id_question" name="question_description" class="full-width"></textarea>
<span id="error_body"></span>
<p>
<label for="id_tags" class="inline-block">Tags</label>
<input type="text" id="id_newstagbox" name="question_tags"/>
</p>
<span id="error_tags"></span>
<button class="btn btn-success" type="submit">Post your question</button>
</form>
JS
function validateForm()
{
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
return false;
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
return false;
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
return false;
}
}
After submitting the forms post successfully if title is present.
The stackoverflow form validation forced me to do this, its constantly saying me to add more text because my question contains mostly code.I know its good to provide more information about question but there are times when you can ask a question in few words without being too broad and then you have to rant about it to pass the FORM VALIDATION.
Just remove return false.modify it like below
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["farea"].value;
var z=document.forms["myForm"]["ftag"].value;
if (x==null || x=="")
{
document.getElementById('ern').innerHTML="*Please add a title*";
}
if (y==null || y=="")
{
document.getElementById('era').innerHTML="*Please add a desxription*";
}
if (z==null || z=="")
{
document.getElementById('ert').innerHTML="*Please add a tag*";
}
}
</script>
I prefer using jQuery:
$('#form').submit(function(e) {
var validated = true;
e.preventDefault();
//title validation
if ($('#id_title').val() == "") {
$('#error_title').html("*Please add a title*");
validated = false;
}
//body validation
if ($('#id_question').val() == "") {
$('#error_body').html("*Please add a description*");
validated = false;
}
//tag validation
if ($('#id_newstagbox').val() == "") {
$('#error_tags').html("*Please add a description*");
validated = false;
}
if(validated) {
$(this).unbind('submit').submit();
}
});
You just remove your return false inside each condition,
check this jsfiddle how it works if you remove return false line.
Note:Return false will stop your execution there
Remove the "return false" in the if clauses. This stops your function and the other if clauses wouldn´t get called.
just add 'return' keyword before validateform()
like this
<form name="qaform" class="nice" method="POST" onsubmit="return validateForm()" action="/ask/ask-question/">
Try making these 5 small changes to your validateForm method -
function validateForm() {
var valid = true; // 1
//title validation
if (document.qaform.question_title.value == "") {
document.getElementById('error_title').innerHTML="*Please add a title*";
valid = false; // 2
}
//body validation
if (document.qaform.question_description.value == "") {
document.getElementById('error_body').innerHTML="*Please add a description*";
valid = false; // 3
}
//tag validation
if (document.qaform.question_tags.value == "") {
document.getElementById('error_tags').innerHTML="*Please add a description*";
valid = false; // 4
}
return valid; // 5
}
i think the reason why it only validates the first one, is because you return false to exit the validate function, if you do the return false after all the if loops i think it will do what you want.

JQuery Validation for Two Password Fields

Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
    $(".error").show(500);
}else{
 $(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.

javascript return true not working

i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit

Categories