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
Related
I have short jQuery code trying to check whether either of the text fields is empty. If either is empty then the form won't be submitted. Unfortunately, it submits only if both text fields are filled. That should happen if I use the AND operator, but I am using OR operator. What is the explanation?
The form fields
<form method="post"
name="customerData"
action="ccavRequestHandler.php"
id="merchantFORM"
role="form">
<!-- New item -->
<div class="col-sm-6">
<div class="form-group mb-4">
<h6>Passport</h6>
<input class="form-control" id="paspatou" type="text" name="merchant_param4" />
</div>
</div>
<!-- New item -->
<div class="col-sm-6">
<div class="form-group mb-4">
<h6>Unique ID Number</h6>
<input class="form-control" id="urno" type="text" name="merchant_param3" />
</div>
</div>
The text field id names are "paspatou" and "urno".
I am also checking whether one of the radio buttons are checked or not and that works fine too as I have to detect whether the donor is local or outstation. The only issue is detecting that only one field has to be filled, not both.
if ($("input[name='donationfrom'][value='no']").prop("checked")) {
$("#merchantFORM").on('submit', function (e) {
if ($("input[name='donationfrom'][value='no']").prop("checked")) {
if (($("#paspatou").val().length <= 0) || ($("#urno").val().length <= 0)) {
alert("Please fill either Passport or Unique ID Number");
return false;
}
} else {
return true;
}
});
You should change the code in your inner if statement. You actually need && here as you want to show the alert when both fields are empty.
if (($("#paspatou").val().length <= 0) && ($("#urno").val().length <= 0)) {
alert("Please fill either Passport or Unique ID Number");
return false;
}
Other solution, if you want to keep the OR logic is to change your code like so:
$("#merchantFORM").on('submit', function (e) {
if ($("input[name='donationfrom'][value='no']").prop("checked")) {
if (($("#paspatou").val().length > 0) || ($("#urno").val().length > 0)) {
return true;
}
alert("Please fill either Passport or Unique ID Number");
return false;
} else {
return true;
}
});
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
}
})
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"
}
}
});
I have begun learning javascript and I cannot get the security code part of my form (and I have yet to fix the other things such as card number) to bring up an alert if they have not entered 3 integers, I can get it to alert if the person doesnt enter 3 ints/strings/symbols etc... but > or < 3. However I cannot get it to alert the user if the things they pass are not integers. Thank you!.
edit: so the issue im trying to solve is how to run my is_int function on the theForm.cvs.value im sorry if im unclear its all a bit messy.
<script type="text/JavaScript">
function is_int(value){
if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
return true;
} else {
return false;
}
};
function verification(theForm) {
content = "";
var cardLen = (theForm.cardLength.value).length;
var securitycode = new is_int(theForm.cvs.value);
if (cardLen !== 16) {
content += "Please make sure you've entered 16 digits.";
}
if ((theForm.userName.value).length === 0) {
content += "Please make sure you've entered the correct name.";
}
if ((theForm.month.value) < 1 || theForm.month.value > 12 || theForm.month.value === "" || theForm.month.value === "MM") {
content += "Please make sure the you've entered the correct month.";
}
if ((theForm.year.value) < 2016 || ((theForm.year.value) === "" )) {
content += "Please make sure you've entered the correct expiry year.";
}
if ( !securitycode || ( (theForm.cvs.value).length !== 3) ) {
content += "Please make sure you've entered the correct security code.";
}
if (!content == "") {
alert (content); return false;
}
};
</script>
</head>
<body>
<br>
<br>
<br>
<center><h1>Checkout:</h1></center>
<div style="position:absolute; left:600px; top:200px;">
<form name="myForm" class="theForm" onSubmit="return verification(this)" >
Card Number: Expiration:
<br>
<input type="text" name="cardLength"> <input type="text" name="month" style="width:30px" value="MM"> - <input type="text" name="year" style="width:30px" value="YY">
<br>
Name: Security Code:
<br>
<input type="text" name="userName"> <input type="text" name="cvs" style="width:30px">
<br>
<br>
<input type="submit" value="Submit">
</form>
</div>
You don't want to create a new is_int. New creates an instance of an object and calls its constructor, but you just need to get a return value from a function.
if ( !is_int(theForm.cvs.value) || theForm.cvs.value.length !== 3 ) {
content += "Please make sure you've entered the correct security code.";
}
I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you