Alert if form is empty - javascript

How do I check if the whole form is empty and alert it? The form should be able to send even if there's a few empty inputs.
Edit:
Maybe I should've said that it's suppose to be JavaScript or jQuery.
And a better description:
I've got a form with one part that contains 10 input fields, you only have to fill out one.
The other part you only have to fill out name and phone or email but it's 4 fields you could fill with info.
And at last a checkbox making sure the user knows he or she didn't fill out the whole form.
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.

Here is quick and dirty way using pure JavaScript:
function checkForm​(oForm) {
for (var i = 0; i < oForm.elements.length; i++) {
if (GetElementValue(oForm.elements[i]).length > 0)
return true;
}
alert("all empty");
return false;
}
function GetElementValue(element) {
if ((element.type === "checkbox" || element.type === "radio") && element.checked === false)
return "";
return element.value;
}
​Live test case.

create a validate method like this in JS (extend the Switch for other form Elements like radio or checkbox inputs):
function validateForm(domForm) {
var elements = domForm.elements;
var hasData = false;
var isAEmptyString = function(string) {
if(string) {
return string.length() == 0;
}
return true;
};
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
switch(element.tagName.toLowerCase()) {
case 'textarea':
if(!isAEmptyString(element.innerHTML)) {
return true;
}
break;
case 'input':
if(!isAEmptyString(element.value)) {
return true;
}
break;
case 'select':
if(element.selectedIndex >= 0) {
return true;
}
break;
}
}
return false;
};
you can call it in your form onSubmit handler
<form onsubmit="return validateForm(this);">
<textarea name="a"></textarea>
<input type="text" name="b"></input>
<select name="c">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<input type="submit" />
</form>

I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
If that is the case just put a boolean check in your code
var haveAnyErrorsTriggered = false;
// loop through fields and if any are empty change the haveAnyErrorsTriggered to true
// then
if(haveAnyErrorsTriggered){alert("One or more fields are empty.");}
if you want to check if the whole form is empty, just do the opposite
var isAtLeastOneFieldFull = false;
// loop through fields and if any are not empty change the isAtLeastOneFieldFull to true
// then
if(!isAtLeastOneFieldFull){alert("all the fields are empty");}

You are talking about Javascript form validation. Create a Javascript function (called say validateForm) that validates the fields in your form, and pops up an alert if it detects an error. It should return true if the form is to be submitted, and false if there is an error. Then in the your HTML form tag, add the clause onsubmit="return validateForm()", where validateForm is the name of your function.

Maybe the form fields listener example I once cooked in this jsfiddle can help you further? Note that client side validation will never be enough. Anyone can tamper with the javascript in your page, so you allways have to validate a form server side too.

Related

JS->Form validation on inputs. Using for loop to get all the inputs index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.
After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === ""
using a variable to make the querySelector("THE CLASS").style.display="block";
Also on my form I have this line
<form method="post" class="q-form" name="form" onsubmit="return validate()">
My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.
Let me know if there is something more to clarify.
Here you have all the code: https://jsbin.com/kazopahuga/1/edit?html,js,output
If you want to see the alert showing press Run with JS
Thank You!
I suggest a few modifications to your validare() function:
Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.
var isValid = true;
Capture your validation messages too so you can access them by index like your inputs:
messages = document.getElementsByClassName(' alert alert-danger custom');
When you find an invalid input, display the associated message and update the valid flag to false.
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
Here is the updated function:
function validare() {
var inputs, messages, index;
var isValid = true;
inputs = document.getElementsByTagName('input');
messages = document.getElementsByClassName(' alert alert-danger custom');
for (index = 0; index < inputs.length; ++index) {
var currentInputValue = inputs[index].value;
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
}
return isValid;
}
Updated jsbin here
Here is an updated solution: jsbin
You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

JavaScript many input control null or not

I have 350 text inputs in the form. I want to control those for empty or not. I know for one input eg:
var ism=document.getElementById('inputtext').value;
if(ism.length==0){
return false;
}
But I have inputs :
<input type="text" name="inputtext[]"/>
What I do ?
You may want to consider the HTML 5 way; adding the required attribute to prevent form submission with empty inputs
<input type="text" required />
Trying to submit without putting anything in this will cause a message to be shown and submission prevented
Any method you choose should still have server-side validation
You check all of them I suppose ?
var inputs = document.querySelectorAll('[name="inputtext[]"]'),
isEmpty = false;
for (var i=inputs.length; i--;) {
if ( inputs[i].value.length === 0 ) {
isEmpty = true;
break;
}
}

Form validation inside a loop in php

I have a commenting system in PHP, in which there is loop to fetch articles. every article has a comment form which needs to be validated for null values.
Now problem is there is no limit to the number of these forms and ID of each form is coming from database. I want to validate each form but without writing the script multiple times.
How can i validate the form field for null value without writing script again & again.
Can i create a loop kind of thing in my script which check the field for null values.
My script is like this -
function validatecomments()
{
nums = ["1", "2", "3", "4"];
text = "commentform"; //form id is like this - commentform1, commentform2, ...
for (var i = 1; i < nums.length; i++) {
text = text + nums[i]; //to create it like form id
if (document.text.comment_emp_id.value=="")
{
alert("Please enter the Employee ID");
document.text.comment_emp_id.focus();
return false;
}
if (document.text.comment.value=="")
{
alert("Please give some Comments");
document.text.comment.focus();
return false;
}
}
}
this is snapshot of the comment form. here are 2 forms with POST button. Problem is i have a number of such forms in a page and i have to check them for null values. I am being forced to write script code multiple times.
Can anyone help me out.
you are not sending correct value to the script. try this
<form name="commentform<?php echo $your_id?>" action="" onSubmit="return validatecomments(this);" method="post">
in your script
function validatecomments(f)
{
if (f.elements['comment_emp_id'].value=="")
{
alert("Please enter the Employee ID");
f.elements['comment_emp_id'].focus();
return false;
}
else if (f.elements['comment'].value=="")
{
alert("Please give some Comments");
f.elements['comment'].focus();
return false;
}
}
May be it helps you.

Focus on first invalid text field after form validation

I have a pretty standard HTML form in which I collect user input. I have a submit button that will run a JavaScript function (onClick) that in turn validate the data entered by the users.
The function looks like this:
function validateForm()
{
var isValid = true;
var txtFirstname = document.getElementById("firstName").value;
var txtLastname = document.getElementById("lastName").value;
(etc...)
/*Validate First Name*/
if(txtFirstname.length <= 0){
document.getElementById("lblFirstName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblFirstName").innerHTML="";
document.getElementById("firstName").value = txtFirstname;
}
/*Validate last Name*/
if(txtLastname.length <= 0){
document.getElementById("lblLastName").innerHTML=" *";
isValid = false;
}
else{
document.getElementById("lblLastName").innerHTML="";
document.getElementById("lastName").value = txtLastname;
}
(etc...)
if(isValid){
document.formX.submit();
}
else{
return false
}
}
My question is: how can I set the focus on the first "invalid" textbox after the function has validated the form?
Thanks,
Eric
i search 4 it & find a better popular solution :
`$("#"+document.querySelectorAll(":invalid")[1].id).focus();`
it's work for me. note that index of first invalid input in Firefox is 1 not 0. because of in FF the form is invalid and count, when an invalid input exist.
It would be cleaner if you functionally decomposed your validation. Then you could have a variable called "firstInvalidField" which is initially set to null. Upon invalidation of a field, check to see if firstInvalidField is null, if it is, set it to the textBox in question. If it is not null, skip over the code.
After the validation is complete, if the firstInvalidField variable is not null, call .focus() on it.

Javascript form validation - multiple form fields larger than 0

function negativeValues(){
var myTextField = document.getElementById('digit');
if(myTextField.value < 0)
{
alert("Unable to submit as one field has a negative value");
return false;
}
}
Above is a Javascript piece of code where every time a field id 'digit' has a value that's less than 0, than an alert box appears either onsubmit or onclick in the submit button.
There are about 50 fields in the form that should be considered 'digit' fields where they shouldn't be anything less than 0. What should I change with this Javascript to ensure that all 'digit' like fields have this alert box pop up?
I cannot use jquery/mootools for validation - it has to be flat Javascript.
Thanks.
var form = document.forms[0]; // first form in the document
form.onsubmit = function () {
for (var i=0; i<this.elements.length; i++)
if (Number(this.elements[i].value) < 0) {
alert("Unable to submit as one field has a negative value"); // complain
return false; // and prevent submission
}
}
Do not give ID="digit", ids need to be unique. Instead give a class="digit" or name="digit[]" which in PHP will give you an array on the server.
Here is a typical validation using forms access
function validate(theForm) {
var el = theForm.elements;
for (var i=0,n=el.length;i<n;i++) {
if (el[i].className=="digit" && parseInt(el[i].value,10)<0) {
alert('This field must contain a value > 0');
el[i].focus();
return false;
}
}
return true; // allow submission
}
assuming
<form onsubmit="return validate(this)">
Alternatives for the className== would be
if (el[i].className.indexOf('digit')!=-1
if the className could be manipulated from elsewhere.
You can use ID="digit1" ID="digit2" and
if (el[i].id.indexOf('digit')==0

Categories