How to Validation that User should enter any of two field - javascript

form html
<form action="" method="post" name="add_new_report" id="add_new_report" enctype="multipart/form-data" onsubmit="return AddNewReport(this)">
<div class="field">
<div class="field_180">Cheque</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cheque" id="cheque" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_180">Cash</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cash" id="cash" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_210"> </div>
<div class="field_222">
<input type="submit" id="Submit" name="Submit" value="Submit" />
</div>
<div class="clear"></div>
</div>
</form>
in this form user should enter either cheque or cash Field how is it possible ? i don't want to be both are mandatory.

If you absolutely do not care about IE <9 you could use something like the following. (otherwise replace the code not working in IE, with some that does)
function oneShouldHaveData(ids) {
var elements = [];
//convert ids to elements (map no IE<9)
elements = ids.map(function (id) {
return document.querySelector('#' + id);
});
//returns true if any element matches expression (some no IE <9)
return elements.some(function (element) {
//could be validation for anything (greater 0 etc.)
return !!element.value;
});
}
//just submit setup :)
document.querySelector('#add_new_report').addEventListener('submit', function () {
console.log(oneShouldHaveData(['cheque', 'cash']));
});
http://jsfiddle.net/LXprX/1/

Simply add this function to your header:
<script>
function validateForm()
{
var x=document.forms["add_new_report"]["cheque"].value;
var y=document.forms["add_new_report"]["cash"].value;
if ((x==null || x=="") && (y==null || y==""))
{
alert("At least one entry should be filled");
return false;
}
else
return true
}
</script>
and change the following field:
onsubmit="if(validateForm()) return AddNewReport(this)"
You can also include AddNewReport in validateForm function and only return validate(this) function.

Related

Prevent refresh of page after alert

I am trying to validate a form. I am successful on that, but if the alert kicks in, the page refresh and since i am using a pop up, this one closes and i have to open it again. I need to prevent that in the case of a miss click.
Here are the code:
HTML
<div class="row">
<form action="" method="" id="formBoard" name="formOfBoard">
<div class="col-75">
<label for="bname">Name of the Board: </label><br>
<input type="text" id="boardname" name="boardname">
</div>
<div class="row">
<div class="col-75">
<label for="ipadd">IP Address:</label><br>
<input type="text" name="ipadd" id="ipaddress">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="portnum">Port:</label><br>
<input type="text" name="portnum" id="portnum">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="imgadd">Upload image:</label><br>
<img src="node_modules/#tabler/icons/icons-png/file-upload.png" alt="Insert image" class="insrtimg" name="imageboard" id="insertimage">
</div>
</div>
<div class="row">
<div class="col-80">
<div>
<div class="btnfrm" style="background-color: #F30D0DBF; color:antiquewhite" onclick="closeForm()">Discard</div>
<input type="submit" class="btnfrm" style="background-color: rgb(67, 221, 67);" value="Save" onclick="validateIndexForm()">
</div>
</div>
</div>
</form>
</div>
</form>
</div>
JavaScript
function validateIndexForm(){
let x = document.getElementById("boardname").value;
let y = document.getElementById("ipaddress").value;
let z = document.getElementById("portnum").value;
let w = document.getElementById("insertimage").value;
let ipfrmt = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;;
if(x == ""){
alert("Please insert the boards name");
return false;
}
if(!y.match(ipfrmt)){
alert("Please insert a valid IP address");
return false;
}
if(z != isNaN() && !(z > 0)){
alert("Please insert the correct port");
return false;
}
return x, y, z;
}
The likely reason for the reload may be from the form action that is returning the default values into the URL, meaning it is causing new navigation (this can be seen in the dev console, such as chrome, by turning this on via the dev tool preferences.
I have tested this only with the HTML/JavaScript so not sure what other parts of the application are doing but hopefully this helps.
Change the button onclick to the form onsubmit action
passing through the event to the function
prevent default when an error occurs
<div class="row">
<form action="" method="" id="formBoard" name="formOfBoard" onsubmit="validateIndexForm(event)">
<div class="col-75">
<label for="bname">Name of the Board: </label><br>
<input type="text" id="boardname" name="boardname">
</div>
<div class="row">
<div class="col-75">
<label for="ipadd">IP Address:</label><br>
<input type="text" name="ipadd" id="ipaddress">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="portnum">Port:</label><br>
<input type="text" name="portnum" id="portnum">
</div>
</div>
<div class="row">
<div class="col-75">
<label for="imgadd">Upload image:</label><br>
<img src="node_modules/#tabler/icons/icons-png/file-upload.png" alt="Insert image" class="insrtimg" name="imageboard" id="insertimage">
</div>
</div>
<div class="row">
<div class="col-80">
<div>
<div class="btnfrm" style="background-color: #F30D0DBF; color:antiquewhite" onclick="closeForm()">Discard</div>
<input type="submit" class="btnfrm" style="background-color: rgb(67, 221, 67);" value="Save" >
</div>
</div>
</div>
</form>
</div>
</form>
</div>
function validateIndexForm(event){
let x = document.getElementById("boardname").value;
let y = document.getElementById("ipaddress").value;
let z = document.getElementById("portnum").value;
let w = document.getElementById("insertimage").value;
let ipfrmt = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;;
if(x == ""){
event.preventDefault();
alert("Please insert the boards name");
return false;
}
if(!y.match(ipfrmt)){
event.preventDefault();
alert("Please insert a valid IP address");
return false;
}
if(z != isNaN() && !(z > 0)){
event.preventDefault();
alert("Please insert the correct port");
return false;
}
return x, y, z;
}
Note: to make further improvements to the lines of code that are repeated (prevent default) the function could be broken out into a validation function that returns true or false based on the inputs.

jQuery .each through few text inputs instead of javascript .find function

I want to make validation for my input text form, that user cannot go further unless all input forms will be completed. i want to make it through every input that even if first is completed, user needs to complete another 2 etc. but at this moment i am only able to make it through the first one and have no idea how to iterate it through every input text.
My html:
<div class="write-to-us">
<div class="col-md-12 field">
<p>Write to us</p>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Name</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your Name</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Surname</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your surname</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label">Question</label>
<textarea type="text" name="subject" class="my-text-input"></textarea>
</div>
</div>
<div>
<button class="my-button">Check it</button>
</div>
</div>
And my js code for iteration:
myFunction: function() {
var $formField = $('.write-to-us');
if (!$formField.exists()) {
return;
}
initValidation();
function initValidation() {
var errorMsg = $formField.find('.label-error');
var button = $formField.find('.my-button');
var input = $formField.find('input');
var inputContainer = $formField.find('.my-form')
button.click(function(event) {
if(!input.val().trim()) {
errorMsg.css('visibility', 'visible');
inputContainer.addClass('error');
event.preventDefault();
}
});
},
I guess that problem is with .find and should be some jQuery .each but i have no idea how to change it.
I would try doing something like this rather than find.
function initValidation() {
$('.my-button').click(function(){
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my-form').addClass('error');
}
});
});
}

Validating all form fields -- function not working correctly

I created a html form and a function validateForm() to validate the form fields. However the function is only reporting issues with wrong email input, and its not validating the other fields in the form. Can you check my code to see if i have any errors.
Thanks
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Support Center</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/layout.css" type="text/css">
<link rel="stylesheet" href="styles/Form.css" type="text/css">
<script type="text/javascript" src="Form.js"></script>
</head>
<body>
<div class="wrapper row1">
<header id="header" class="clear">
<div id="hgroup">
<h1>Support Center</h1>
<h2>Welcome to our website</h2>
</div>
<nav>
<ul>
<li>Home</li>
<li>Our Staff</li>
<li>Location</li>
<li>Help</li>
<li class="last"></li>
</ul>
</nav>
</header>
</div>
</body>
<!-- content -->
<body>
<h1>Help is here!</h1>
<form>
<h1>Should you need assistance, please do not hesitate to contact us:</h1>
<div class="contentform">
<div id="sendmessage"> Your form has been sent successfully. Thank you. </div>
<div class="leftcontact">
<div class="form-group">
<p>Surname<span>*</span></p>
<span class="icon-case"><i class="fa fa-male"></i></span>
<input type="text" name="lastName" id="lastName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>First Name <span>*</span></p>
<span class="icon-case"><i class="fa fa-user"></i></span>
<input type="text" name="firstName" id="firstName"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>E-mail <span>*</span></p>
<span class="icon-case"><i class="fa fa-envelope-o"></i></span>
<input type="email" name="emailAddress" id="emailAddress"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Office <span>*</span></p>
<span class="icon-case"><i class="fa fa-location-arrow"></i></span>
<input type="text" name="office" id="office"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Desk <span>*</span></p>
<span class="icon-case"><i class="fa fa-map-marker"></i></span>
<input type="text" name="deskNumber" id="deskNumber"/>
<div class="validation"></div>
</div>
</div>
<div class="rightcontact">
<div class="form-group">
<p>Phone number <span>*</span></p>
<span class="icon-case"><i class="fa fa-phone"></i></span>
<input type="text" name="mobilePhone" id="mobilePhone"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Job Number <span>*</span></p>
<span class="icon-case"><i class="fa fa-building-o"></i></span>
<input type="text" name="jobNumber" id="jobNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Computer <span>*</span></p>
<span class="icon-case"><i class="fa fa-info"></i></span>
<input type="text" name="computerNumber" id="computerNumber"/>
<div class="validation"></div>
</div>
<div class="form-group">
<p>Problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comment-o"></i></span>
<select name="Problem">
<option value="New User">New User</option>
<option value="Delete User">Delete User</option>
<option value="Lost File">Lost File</option>
<option value="New Software Installation">New Software Installation</option>
<option value="Virus Checking">Virus Checking</option>
</select>
<div class="validation"></div>
</div>
<div class="form-group">
<p>A little about your problem <span>*</span></p>
<span class="icon-case"><i class="fa fa-comments-o"></i></span>
<textarea name="message" rows="14"></textarea>
<div class="validation"></div>
</div>
</div>
</div>
<button type="submit" class="bouton-contact">Send</button>
</form>
</body>
</html>
</body>
</html>
Code
function validateForm() {
var letters = "[A-Za-z]+$";
var numbers = "^[0-9]+$";
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var jobNumber = document.getElementById("jobNumber").value;
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var mobilePhone = document.getElementById("mobilePhone").value;
var emailAddress = document.getElementById("emailAddress").value;
var officeNumber = document.getElementById("office").value;
var deskNumber = document.getElementById("deskNumber").value;
var computerNumber = document.getElementById("computerNumber").value;
if(jobNumber != "" && firstName != "" && lastName != "" && mobilePhone != "" && emailAddress != "" && officeNumber != "" && deskNumber != "" && computerNumber != "") {
if(jobNumber.length == 5 && jobNumber.match(numbers)) {
if(firstName.match(letters) && lastName.match(letters)) {
if(mobilePhone.length == 10 && mobilePhone.match(numbers)) {
if(emailAddress.match(emailReg)) {
alert("Form submitted!");
return true;
}
else {
alert("Please enter a valid email");
return false;
}
}
else {
alert("Please enter a valid mobile number");
return false;
}
}
else {
alert("Please enter a valid first name and last name");
return false;
}
}
else {
alert("Please enter a valid job number");
return false;
}
}
else {
alert("Please enter in all fields");
return false;
}
}
Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several.
Also, the reason the email is the only one working is because the browser is validating the email without using your JS.
First I would ditch all the variables declared and replace it with the form object.
var formObject = document.getElementById('contentform');
Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.
var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
errorList.push('Please enter a valid job number');
isValid = false;
}
Then rinse and repeat for each element required. After that, just return the list and status (isValid).
// this should be on its own at the bottom of your function right before you return
if (!isValid) {
alert(errorList);
// I would add some formatting or preferably display in the form view.
}
return isValid;
html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>
Also, these
if (!isValid) {
alert(errorList);
}
should be removed from each if statement and placed at the bottom after all have been checked.
Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.
//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />
//javascript
function validation()
{
var email = document.getElementById('email').value;
if(email == '' || !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
{
document.getElementById('emailerror').style.display = 'inline';
var error=1;
}
else
{
document.getElementById('emailerror').style.display = 'none';
}
if(error == 1)
{
return false;
}
else
{
return true;
}
}
now your email validation works fine, thanks

JavaScript - Bootstrap Validator

I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)
I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>

jQuery Validate forms by sections

i am trying to use jQuery validate to validate a big form that i have cut in 3 different sections.
personal information
job information
additional information
is there a way for me to validate the content every time the user hits continue? and then when they get to the last section they can submit the ENTIRE form?
form
<form method="post" name="form" id="form" class="form">
<div class="section_one form-wrapper-top-margin active">
<div class="columns-2 float-left">
<input name="name" id="name" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="email" id="email" type="text" class="" value=""/>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_1"/>
</div>
</div>
<div class="section_two form-wrapper-top-margin">
<div class="columns-1 margin-0">
<input name="address" id="address" type="text" class="" value=""/>
</div>
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="button" type="button" value="Continue" id="btn_2"/>
</div>
</div>
<div class="section_there form-wrapper-top-margin">
<div class="columns-1 margin-0">
<textarea name="description" id="description" type="text" class=""></textarea>
</div>
<div class="columns-2 float-right margin-0">
<input name="submit" type="submit" id="submitbtn" value="Send your message"/>
</div>
</div>
</div>
</div>
</form>
i dont put the jQuery code here because i dont know where to start. i know jQuery validate, validates an entire form, but i never seen it done by sections with out splitting it into 3 different forms.
Thanks for the help...
You can do like this also:-
$(".section_two").click(function(){
//Your code for validation of section one.
});
$(".section_three").click(function(){
//Your code for validation of section one and section two.
});
$("#submitbtn").click(function(){
//Your code for validation of section three.
});
Let me know if this helps.
I found the answer here:
jQuery button validate part of a form at a time
this is the code i used
var validator = $('#form').validate({
ignore: 'input.continue,input#submitbtn',
rules: {
name: {
required: true
},
email: {
required : true
},
date: {
required: true
},
},
messages: {
name: "Enter your name",
email: {
require: "Please enter a valid email address",
email: "Enter a valid email"
},
},
errorPlacement: function(error, element) { },
});
$('#continue1').on('click', function(){
var tab = $(".section_one.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-1080px'});
}
});
$('#continue2').on('click', function(){
var tab = $(".section_two.active");
var sec1 = $('.inner_section_container');
var valid = true;
$('input', tab).each(function(i, v){
valid = validator.element(v) && valid;
});
if(!valid){
return;
}else{
$('.inner_section_container').animate({'left':'-2160px'});
}
});
thanks for everyone's advise...

Categories

Resources