EDIT2:
I feel I'm near the solution. Following the vicgoyso's suggestion I created some object from my inputs (and not arrays), and then I compared them: see the jsfiddle
Since this comparison is working: comparison on jsfiddle I would expect the code above to work as well, but it's not.
EDIT:
The jQuery method I was working on is similar to this:
$().ready(function(){
$.validator.addMethod("same_names", function(value, element) {
if (!$('#surname').val() || $('#surname').val() != null
&& !$('#surname1').val() || $('#surname1').val() != null){
return $('#name').val() != $('#name1').val()
&& $('#surname').val() != $('#surname1').val()
&& $('#nickname').val() != $('#nickname1').val()
}
}, " Your input is equal to another");
$("#myForm").validate({
rules: {
name: {
required: false,
same_names: true
},
name1: {
required: false,
same_names: true
},
surname: {
required: false,
same_names: true
},
surname1: {
required: false,
same_names: true
},
nickname: {
required: false,
same_names: true
},
nickname1: {
required: false,
same_names: true
},
},
messages: {
...
}
})
});
It continue say that name, surname and nickname are required, and they are not.
Without jQuery my method is similar to this:
$('#myForm').submit(function (event) {
var errors = false;
if ($('#name').val() == $('#name1').val() &&
$('#surname').val() == $('#surname1').val() &&
$('#nickname').val() == $('#nickname1').val()
||
$('#name').val() == $('#name2').val() &&
$('#surname').val() == $('#surname2').val() &&
$('#nickname').val() == $('#nickname2').val()
||
$('#name').val() == $('#name3').val() &&
$('#surname').val() == $('#surname3').val() &&
$('#nickname').val() == $('#nickname3').val()
||
$('#name').val() == $('#name4').val() &&
$('#surname').val() == $('#surname4').val() &&
$('#nickname').val() == $('#nickname4').val()
....
||
$('#name').val() == $('#name10').val() &&
$('#surname').val() == $('#surname10').val() &&
$('#nickname').val() == $('#nickname10').val()
||
$('#name1').val() == $('#name2').val() &&
$('#surname1').val() == $('#surname2').val() &&
$('#nickname1').val() == $('#nickname2').val()
||
$('#name1').val() == $('#name3').val() &&
$('#surname1').val() == $('#surname3').val() &&
$('#nickname1').val() == $('#nickname3').val()
.... and so on
) {
$("#error").show();
location.href = "#";
location.href = "#error";
errors = true;
} else {
errors = false;
$("#error").hide();
}
if (errors == true) {
event.preventDefault();
}
});
My actual jsp is similar to this (there are 10 input groups, formed by name + surname + nickname):
<form id="myForm" method="post">
<input id="name" name="name" />
<input id="surname" name="surname" />
<input id="nickname" name="nickname" />
<br/ >
<input id="name1" name="name1" />
<input id="surname1" name="surname1" />
<input id="nickname1" name="nickname1" />
<br/>
<input id="name2" name="name2" />
<input id="surname2" name="surname2" />
<input id="nickname2" name="nickname2" />
<br />
<input id="name3" name="name3" />
<input id="surname3" name="surname3" />
<input id="nickname3" name="nickname3" />
<br />
<br />
<input id="submit" type="submit" value="submit" />
</form>
I want to be an error just if one of this group (name, surname, nickname) is equal to another, for example this is an error:
John
Smith
prince *
John
Smith
prince *
John
Smith
snowman
But this one is not:
John
Smith
prince at least one field is different so the input is fine
John
Smith
snowman *at least one field is different so the input is fine
John
Smith
fireball at least one field is different so the input is fine
QUESTION
What if I want to use this code: https://stackoverflow.com/a/16965721/4477899
To solve this problem here: Form validate some input must be different from each other
I'm asking because I'm already using jQuery validate, and the previous approach is not working well if fields are more than two groups, or are empty (those fields are not required).
Regarding this part only:
EDIT2:
I feel I'm near the solution. Following the vicgoyso's suggestion I created some object from my inputs (and not arrays), and then I compared them: see the jsfiddle
Since this comparison is working: comparison on jsfiddle I would expect the code above to work as well, but it's not.
You failed to include jQuery itself in the jsFiddle.
Mainly it wouldn't work anyway because your boolean logic is backwards. You are getting true when you find a match. However, you then return true from the addMethod() method, so with a true you are telling it to PASS validation. To fail validation, you must return false instead.
return !duplicateFound;
Finally, to make the fields optional, you'll need a little more logic...
return this.optional(element) || !duplicateFound;
DEMO: https://jsfiddle.net/awb4tcyy/3/
As a general note, your code will get incredibly complex as you scale with more groups of fields. I would suggest you leverage some type of looping algorithm. Good luck.
You first need to define a custom validation method:
https://jqueryvalidation.org/jQuery.validator.addMethod/
jQuery.validator.addMethod("laxEmail", function(value, element) {
var duplicateFound = false;
//apply input values in array
//check for duplicates
duplicateFound = true; //update variable if duplicate found
return duplicateFound;
}, 'Input values cannot be identical');
In your custom validation, get/store the input values in an array:
jQuery get values from inputs and create an array
then check array for duplicates, return true if duplicate is found:
How can I check if the array of objects have duplicate property values?
You then add the name of your custom validation rule to the input validation like so:
myForm.validate({
rules: {
myCustomRule: {
required: true
}
},
messages {
myCustomRule: {
required: "Input values cannot be identical"
}
}
});
Related
I have 4 textboxes, and I need to make sure that before submitting I have at least one of the textboxes filled.
HTML:
<form name="parentForm">
<input name="pf1" id="pf1" type="text">
<input name="pf2" id="pf2" type="text">
<input name="pf3" id="pf3" type="text">
<button type="button" onClick="submit()">Submit</button>
</form>
Javascript:
function submit()
{
if ($.trim($("#pf1").val()) === "" || $.trim($("#pf2").val()) === "" || $.trim($("#pf3").val()) === "")
{
alert ('Fields are empty.');
return false;
}
...
}
the problem is that it only submit if all fields are filled, in my case what iI want is that if only 1 textbox has data, I can submit the form.
Instead of || operator use && operator to check for all inputs.
Instead you can compare the count of empty inputs with the total inputs using filter. If they are equal, it mean all input fields are empty.
function submit() {
const emptyInputs = $('input').filter(function() {
return $(this).val().trim() == "";
});
if (emptyInputs.length === $('input').length) {
alert('Fields are empty.');
return;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="pf1" id="pf1" type="text">
<input name="pf2" id="pf2" type="text">
<input name="pf3" id="pf3" type="text">
<button type="button" onClick="submit()">Submit</button>
if only one field must be filled with a value change your or to and
function submit()
{
if ($.trim($("#pf1").val()) === "" && $.trim($("#pf2").val()) === "" && $.trim($("#pf3").val()) === "")
{
alert ('Fields are empty.');
return false;
}
...
}
Make a loop on all inputs and if at least one is different than empty submit:
$("input").each(function(){
if($(this).val() != ""){
// submit
}
})
My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?
You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/
« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...
You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>
I have sample form.
<form id="test_frm" name="test_frm" class="form" method="post">
<fieldset data-pattern="stripes">
<div>
<label class="req"><i>*</i> Location</label>
<div class='form-search-dropdown'>
<input type='text' class='form-search-field' name='' value=''><i class='form-icon dropdown'></i>
<ul id="sub_maintenance_locations">
{foreach from=$locations item="location"}
<li val="{$location->getId()}">{$location->getName()}</li>
{/foreach}
</ul>
<input type='hidden' class='dropdown-val' id="location_id" name='sub_maintenance_template[{$sub_maintenance_template_count}][location_id]' value=''>
</div>
</div>
<div>
<label class="req"><i>*</i> Problem</label>
<div class='form-search-dropdown'>
<input type='text' class='form-search-field' name='' value=''><i class='form-icon dropdown'></i>
<ul id="problems">
{foreach from=$problems item="problem"}
<li val="{$problem->getId()}">{$problem->getName()}</li>
{/foreach}
</ul>
<input type='hidden' class='dropdown-val' id="problem_id" name='sub_maintenance_template[{$sub_maintenance_template_count}][problem_id]' value=''>
</div>
</div>
<div>
<label class="req"><i>*</i> Description</label>
<textarea class="form-textarea" id="sub_task_description" name="sub_maintenance_template[{$sub_maintenance_template_count}][description]" style="height:120px;"></textarea>
<i class="help"></i>
</div>
<div class="form-submit-container">
<div class="pad">
<input type="button" class="form-submit js-create-subtask" value="Create Sub-task">
<span>or <a>Cancel</a></span>
</div>
</div>
</fieldset>
</form>
I am trying to vallllidate the form without making server call.
Validation code will be llike this -
$(document).off( 'click', '.js-create-subtask' ).on('click', '.js-create-subtask', function(e) {
e.preventDefault();
boolIsValid = true;
$('.js-no-subtasks').hide();
$('#error_div .error').text('');
if( '' == $('#maintenance_location_id').val() || '' == $('#maintenance_problem_id').val() || '' == $('#days_to_complete').val() ){
$('#error_div .error').append('<i></i> Location is required. Problem is required. Days to complete is required.');
$('#error_div .error').show();
boolIsValid = false;
} else if ( '' == $('#maintenance_problem_id').val() ){
$('#error_div .error').append('<i></i> Problem is required.');
$('#error_div .error').show();
boolIsValid = false;
} else if( '' == $('#days_to_complete').val() ){
$('#error_div .error').append(' <i></i> Days to complete is required.');
$('#error_div .error').show();
boolIsValid = false;
} else if( '' == $('#sub_task_description').val() ){
$('#error_div .error').append(' <i></i> Description is required.');
$('#error_div .error').show();
boolIsValid = false;
}
if( true == boolIsValid ) {
// if everything is fine.
}
});
First time whenever I tried for blank values it shows me right validation. But after selecting location from the drop down still it gives me validation location is required.(1st if case because problem & number of days not entered.) Is there any way that I get validation message without nested if cases?
Expected result :
If user did not entered location,problem,no.of days complete &
description it should execute first if case.
If user selected
location only it should show remaining error messages & vice versa.
Your first if statement should use && instead of ||, otherwise it will always display the first message as long as you have one field missing.
if( '' == $('#maintenance_location_id').val() && '' == $('#maintenance_problem_id').val() && '' == $('#days_to_complete').val() ){}
if( '' == $('#maintenance_location_id').val() || '' == $('#maintenance_problem_id').val() || '' == $('#days_to_complete').val() ) will be true when AT LEAST ONE OF THE CONDITIONS IS MET, hence it does not matter you already selected a maintenance location, as long as the other two selects have not been picked, that if will be true and WILL NOT run the other conditions since they are in the form of else if.
This is why: But after selecting location from the drop down still it gives me validation location is required.
Regarding your expected results, you will need an if-else structure for 2^3=8 situations, and show a message for each.
This is only considering #maintenance_location_id, #maintenance_problem_id and #days_to_complete, not #sub_task_description which you do not include in your first if.
false false false
false false true
false true false
true false false
false true true
true false true
true true false
true true true
I will leave that bit to you :). hope it helps
I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you
You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.
In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.
I have 4 input fields and I want to check to see if at least 1 has a value. If none have values I want to return.
Here is what I have and I know if doesn't work because it doesn't enter the if statement if nothing has been entered.
if ($('#Name').val() != "" && $('#State').val() != "" && $('#City').val() != "" && $('#Zip').val() != "") {
showAlert("You need to select at least one of the following: Name, State, City, or Zip", 'error');
return;
}
if none have a value I want to show a message and return without further processing.
So instead of checking that the value is not empty you should check that they ARE empty:
if (!$('#Name').val() && !$('#State').val() && !$('#City').val() && !$('#Zip').val()) {
return alert("You need to select at least one of the following: Name, State, City, or Zip", 'error');
}
You can also put the alert after the return to make it shorter.
Fiddle
You can select all the inputs type text and filter them checking for the value being present:
$(function () {
$("#Check").on("click", function () {
// Will return the inputs containing value.
var anyValue = $("input[type=text]").filter(function () {
return $(this).val().trim() !== "";
});
// If there's at least one containing any value.
console.log(anyValue.length !== 0);
});
});
I considered the markup below:
<input name="Name" id="Name" type="text" placeholder="Name" />
<input name="City" id="City" type="text" placeholder="City" />
<input name="State" id="State" type="text" placeholder="State" />
<input name="Zip" id="Zip" type="text" placeholder="Zip" />
<button id="Check">Check</button>
Demo