Validating check box and input - javascript

i have a form that includes several text inputs and checkboxes (the checkboxes comes from a DB), so... i know how to validate them separetly but i need to validate them together, the way i'm doing this only validate checkboxes, i know why its happening but i don't know how to write the right way... ¿can you help me? here is the code:
<form action="sendreq.php" name="contact" onsubmit="return valida_frm(this)" method="post">
<label>Name</label>
<input name="name" type="text" />
<label>Email</label>
<input name="email" type="text"/><!-- And Severeal inputs then the checkboxes-->
<?php $list3 = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 20");
while($row = mysql_fetch_object($list3)){ ?>
<input id="product" name="product[]" class="label" type="checkbox" value="<?php echo $row->name?>"><label class="label"><?php echo $row->name?></label>
<?php }?>
The Validation doesn't work fine its evident why, i just need the right way to write and unify the return of the alert:
function valida_frm(form){
var alerta="Ooops:\n";
if (form.name.value == "") {alerta+="Name.\n";}
if (form.email.value == "") {alerta+="Email.\n";}
for(var i = 0; i < form.product.length; i++){
if(form.product[i].checked)return true;}
alert('Oooops');
return false;
if (alerta!="Error:\n"){
alert(alerta);
return false;
}else{
return true;
}
}
Thanks for your time!

Do not call a field for "name" and then test form.name since it already has a .name
Then test form["product[]"] and not form.product - you cannot have id="product" since ID has to be unique!
I suggest you give id="product<?echo $somecounter; ?>" />...<label for="product<? echo $somecounter; ?>">...</label>
Also test against Error (or nothing as in my suggesion) and not Oops
Also more issues fixed
DEMO
function valida_frm(form){
var alerta="";
if (form.name.value == "") {alerta+="Name.\n";} // Please use FullName or such
if (form.email.value == "") {alerta+="Email.\n";}
var chks = form["product[]"],
checked = false;
for(var i = 0; i < chks.length; i++) {
if(chks[i].checked) {
checked = true;
break;
}
}
if (!checked) {
alerta+='Product.\n';
}
if (alerta){
alert("Error:\n"+alerta);
return false;
}
return true;
}

Related

How to validate all inputs which exists on page?

All inputs from page
I have this html page which is dynamical created, which contains some divs. Every div-question(0,1,2, etc) contain an input based on which answer type the user chose. I want to validate every single inputs from page and:
If value of one input type number,text,date is != "" alert("something")
else send the value in an array;
If checkbox/radio is not checked alert("something");
I tried something like this:
let nrDiv = document.getElementsByClassName("div-question");
let existInput = nrDiv[0].querySelector("input[type='text']");
let numberInput = nrDiv[0].querySelector("input[type='number']");
if (document.body.contains(existInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container[0].querySelector("input[type='text']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
It's working but if I come with another for loop, for input type="number" is not working anymore. I'm getting value null. So if I come with this:
if (document.body.contains(numberInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container.querySelector("input[type='number']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
And for the checkbox and radio inputs I don't have any idea. I want something like this:
If all inputs are not empty and minimum one checkbox/radio is checked, send the answer and question in an array else alert("error");
I feel like this is simple once you add the required attribute and/or a pattern.
This is a simple POC:
<form action="">
<input type="text" required>
<input type="number" required>
<input type="checkbox" required>
<input type="radio" required>
<input type="date" required>
<button type="submit">Submit</button>
</form>
Notice that when you click the submit button, it does the verification you want, in this case != "".

Limit number of characters in collection of number input fields

I have used the reference from from this question and I want to achieve exactly what the question asked however for multiple input text fields. I would like to restrict the user to not type further and have used getElementsByClassName instead of getElementById.
HTML
<td>
<input id="quantity_scroll" cart_id="<?php echo $cart_row['id']; ?>" min="1" type ="number" max="99" value="<?php echo $cart_row['quantity'] ;?>" oninput = "checkLength()" class="form-control form-quantity" style=" width: 60px;text-align: left;" >
</td>
Javascript
function checkLength(){
var elements = document.getElementsByClassName("form-quantity");
var y;
var ele = elements.length/2;
for(y=0; y < ele; y++){
var length = elements[y].value.length;
if(length <= 2){
return true;
}else{
var value = elements[y].value;
value = value.substring(0, value.length-1);
document.getElementsByClassName("form-quantity")[y].value = value;
}
}
}
However the user is restricted only in the first input box and not in the others. I tried different ways however cannot understand why it isn't happening.
Check the below code. It will restrict users to not enter more than 3 digit numbers. You just need to ensure that all your input fields have the same class form-field:
$(".form-field").on('input', function() {
var enteredVal = $(this).val();
if (enteredVal.length > 3) {
$(this).val(enteredVal.substring(0, enteredVal.length - 1));
console.log('More than 3 characters not allowed.');
return;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='form-field' />

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Form using javascript make field required?

I have a form that uses a javascript file items.js to add new items. So each time form.php is used and the 'add items' buttons is clicked then the new row of fields show to add details.
So for example some of the code is the following to add field item name.
newCell = newRow.insertCell(3);
newCell.innerHTML = '<input class="item_text_area item_name" type="text" name="0_item_' + new_item + '" id="0_item_' + new_items + '" size="20" maxlength="250" />';
How can I edit this .js file to make the Item name field required?
Any help would be appreciated.
Per Jeevan: As you cannot be sure how many items the user submits, I would choose for an approach where all new items have unique class, say dynamicAddedItems.
As Jeevan already said, you can add the following to the form tag to prevent it from submitting if it returns false.
<form onsubmit="return validate();"></form>
With javascript:
function validate(){
var elems = document.getElementsByClassName( 'dynamicAddedItems' );
var allgood = true;
//Loop through all elements with this class
for( var i = 0; i < elems.length; i++ ) {
if( !elems[i].value || !elems[i].value.length ) {
elems[i].className += " error";
allgood = false;
} else {
elems[i].className = "item_text_area item_name dynamicAddedItems";
}
}
//If any element did not meet the requirements, prevent it from being submitted and display an alert
if( !allgood ) {
alert( "Please fill in all the required fields." );
return false;
}
//Otherwise submit the form
return true;
}
This script will add the error class if a field is empty and prevent the form from being submitted. It's up to you how you want to display a field with such a class.
You can use jquery for this. Add a class, in this case 'requiredAttr' to the required fields and then validate on form submit.
<form onsubmit="return validate();">
First Name*: <input class="requiredAttr" type="text" /><br/>
Last Name: <input type="text" /><br/>
<input type="submit" />
</form>
function validate(){
$(".requiredAttr").each(function(){
if($(this).val().length < 1){
alert("please fill in all the required fields.");
$(this).focus();
return false;
}
else{
return true;
}
});
return false;
}
Here is a working fiddle. It also brings the focus on the first un-filled field after the validation alert:
http://jsfiddle.net/YG6mk/2/

Validation values

I'm trying to validate my values for alphabets and numberic as well as checking from database. I have created a function of validation and declaring my onclick button with validation function.
Function:
<script>
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
}
return true;
}
</script>
Sample Form:
<form id="Student" name="Student" method="post" action="nextpage.php">
<input name="StudentID" type="text" id="StudentID" value="<?php echo $StudentID?>"/>
<input name="StudentName" type="text" id="StudentName" value="<?php echo $StudentName?>"/>
<input name="StudentAdd" type="text" id="StudentAdd" value="<?php echo $StudentAdd?>"/>
<input type="submit" name="submit" value="Submit" onclick="return validate();"/>
</form>
I have already declared return validate function instead of calling my nextpage.php. But nothing popup for any alert. Kindly advise.
Thanks
Try including your scripts after the body tag to make sure it only references elements after it has already been loaded. Then put return true inside the else statement.
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
return true;
}
}
Instead of the submit button's onclick, move the function to the form's onsubmit, like:
<form onsubmit="validate()" ...>
For the part of the 'if' statement that returns true you may run into some issues with the alerts() as the browser will be trying to submit the form, but over all it should work.
There is no isNumeric() function in JavaScript (I get Uncaught ReferenceError: isNumeric is not defined). You have to create it on your own: Validate decimal numbers in JavaScript - IsNumeric()

Categories

Resources