the issues with validation on multiple form conditions - javascript

i am trying to test he validation conditions,
this.postalCode == '' || this.countryName === '' || this.floorRoom == '' || this.newCustomerName == '' || this.streetAddress == '' || this.cityTown == '' || this.province == ''
i also have country_other and province_other
country_other and province_other can only exists if the countryName is provided as Other and province is hidden, by default they are declared so they cannot end up in undefined.
wat cnditions i need to modify to check if other is selected in the country, the country_other and province_other is filled up and validation and in other case, the country_other and province can be empty if the country is chosen as canada, because province loads the drop don to select the provinces
the code i tried is above

This will check if the countryName is "Other" and if so, it will check if the country_other and province_other fields are not empty. If the country is not "Other" it will check if the province field is not empty. This way, you make sure that country_other and province_other fields are filled when user selects "Other" as countryName and province field is not required in this case, and also if countryName is not 'Other' province field is required.
const isOtherCountry = this.countryName === 'Other';
if (this.postalCode == '' || this.countryName === '' || this.floorRoom == '' || this.newCustomerName == '' || this.streetAddress == '' || this.cityTown == '' || (!isOtherCountry && this.province == '') || (isOtherCountry && (this.country_other == '' || this.province_other == ''))){
// validation failed
} else {
// validation succeeded
}

Related

Selector to check selected value of all drop down lists

I'm trying to find a way to check wether the value selected of all my drop down lists !='' using just one selector in JQuery.
Instead of :
if ($("#list1").val() != '' && $("#list2").val() != ''
&& $('#list3').val() != '' && $('#list4').val() != '') {
//do stuff
}
Is it possible ?
You can add a class to those elements and code:
var vals = $('select.lists').map(function() {
return this.value;
}).get().join('');
if ( vals != '' ) {
// ...
}

Dropdown list is not holding the value on saving the data

WDrodownList
When I am selecting a value from dropdown list say "Practice List" and clicking on save button, and again modifying that item I can see that the dropdown list is not holding its selected value i.e., "Practice List". Instead it is holding its default value i.e., "My List". How can I make it hold the selected value after saving the data?
Here's my html code:
<select id="{{::prefix}}_Select_Practice" name="FreeTextDrugSchedule" ng-options="option as option.name for option in data.practiceOptions" class="form-control medium" ng-model="data.saveIn" style="margin-bottom: 5px;">
<option value="" selected="selected">My list</option>
</select>
<button id="{{::prefix}}_Button_Submit" class="btn btn-primary" ng-click="validations = null; doSubmit()">{{submitVerb}}</button>
Here's my js file code:
$scope.doSubmit = function (dataToSubmit) {
$scope.submitted = true;
if (dataToSubmit) {
if ($scope.data.saveIn) {
dataToSubmit.dataToSubmit.saveIn = $scope.data.saveIn;
}
$scope.data = dataToSubmit.dataToSubmit ? dataToSubmit.dataToSubmit : dataToSubmit;
}
validateSubmission();
// TODO simplify this validation
if ($scope.EnterDetailsForm.$invalid || $scope.showEffectiveDateError ||
$scope.showEffectiveDateRangeError || ($scope.sigValidations &&
$scope.sigValidations.length)
|| ($scope.data.pharmacy1 && $scope.data.pharmacy1 == $scope.data.pharmacy2)
|| ($scope.showMDD && (!$scope.data.medication.maximumDailyDose || ($scope.showMDD == 'pd' && !$scope.data.medication.maximumDailyDoseUnit)))
|| $scope.showProviderError
|| $scope.showSupervisorError
|| $scope.drugMinError
|| $scope.showPrimaryError) {
$scope.validations.push({
name: 'Invalid Entry',
msg: 'Please correct all errors on this form to continue.'
});
if ($scope.entity == 'Prescription') {
$scope.scrollToError = true;
}
} else if ($scope.entity == 'Prescription' && !validateDuration()) {
$scope.$emit('ghostMessage', 'The length of the prescription should not be more than 365 days');
} else { //proceed with submission
// prepare the data to be submitted to the alert checker
var dataToSubmit = prepareDataToSubmit();
// validate payload before submit
if (dataToSubmit.medication.lastRefillDate && dataToSubmit.medication.startDate && dataToSubmit.medication.lastRefillDate.date < dataToSubmit.medication.startDate.date) {
$scope.$emit('ghostMessage', 'Last written date cannot be before start date.');
} else if (dataToSubmit.medication.lastRefillDate && dataToSubmit.medication.stopDate && dataToSubmit.medication.lastRefillDate.date > dataToSubmit.medication.stopDate.date) {
$scope.$emit('ghostMessage', 'Last written date cannot be after stop date.');
} else if (dataToSubmit.medication.diagnoses && dataToSubmit.medication.diagnoses.length == 2 && dataToSubmit.medication.diagnoses[0].code &&
dataToSubmit.medication.diagnoses[0].code == dataToSubmit.medication.diagnoses[1].code) {
$scope.$emit('ghostMessage', 'You may not specify the same diagnosis code for both primary and secondary diagnoses');
} else if ($scope.entity != 'FavoriteRx' && $scope.showDAWGenericWarning && !$scope.formularyCheckedForDAWWarning) {
checkFormularyAlertsForDAWWarning(dataToSubmit);
} else {
$scope.formularyCheckedForDAWWarning = false;
// check dose alerts if necessary
dataToSubmit.schedules = angular.copy(schedules);
if ($scope.entity == 'Prescription' && doseCheckNeeded) {
checkDoseAlerts(dataToSubmit);
} else { // done; process submission
$scope.submit({data: dataToSubmit, optionCodes: $scope.optionCodes});
$scope.loading = 0;
}
}
}
};
I'm not exactly sure what you are asking for, or what you mean by "saving" the data, but I will try to offer some assistance.
I don't know angular.js, but my suggestion would be to wrap the select in a form (which I assume you're doing) and then set the value using the post value in angluar.js (if you can do that). That way, if you reload the page, it will not load the default value. Additionally, if you're merely inspecting the element in a browser after you select a new option, it won't show you that a new option is selected (i.e. the selected="" attribute will still be on the default).

Javascript Conditions are Executing Either Way

please help me out on this, I realy don't figure out where is the problem.
my code:
function validateForm()
{
var pic = document.getElementById("photo1").value;
pic = pic.split('/').pop().split('\\').pop().replace(/[.][^.]+$/, "");
var x = document.getElementById("gyuruszam");
var gyuru = document.getElementById("gyuruszam").value;
if (gyuru == null || gyuru == "" || gyuru == " ")
{
alert("Gyűrűszám nélkül nem lehet adatot lementeni!");
x.focus();
x.style.borderColor="#C30";
return false;
}
if ((gyuru != pic) && (pic != NULL)){
alert("A kép neve nem egyezik meg a gyűrűszámal!");
return false;
}
}
I don't know why is executing the second if, if I do not select file on the field.
I just want an if condition, if I select file and the gyuru is not equal with the name of the file, then return false with an error message. But if I don't select a file return true(ornot even entering in the loop)
Thank you in advance!
EDIT:
I also try this way:
function validateForm()
{
var pic = document.getElementById("photo1").value;
pic = pic.split('/').pop().split('\\').pop().replace(/[.][^.]+$/, "");
var x = document.getElementById("gyuruszam");
var gyuru = document.getElementById("gyuruszam").value;
if (gyuru == null || gyuru == "" || gyuru == " ")
{
alert("Gyűrűszám nélkül nem lehet adatot lementeni!");
x.focus();
x.style.borderColor="#C30";
return false;
}
else if ((gyuru != pic) && (pic != NULL)){
alert("A kép neve nem egyezik meg a gyűrűszámal!");
return false;
}
}
it's working, but not like I want, because if I upload a file with different name, not equal with gyuru it's return true.
my form data is:
<form...
<input type="text" id="gyuruszam" name="gyuruszam"/>
<input type="file" id="photo1" name="photo1"/>
../form>
AND i CHECK THE RETURNED FILE NAME pic IT'S CORRECT!
I'm sorry I'm not sure of what you want.
Your code has a mistake, NULL does not exists, you should put null.
Second problem: pic cannot be null, it will be an empty string if you don't select a file.
So I guess you are looking for:
} else if ((gyuru != pic) && (pic != null) && (pic != '')) {
Try it here: http://jsfiddle.net/nyothecat/ALjGJ/

javascript form validation with multiple if statements

is this form validation function correct? or it can be done better ?
For example: I want one of the two drop-downs to have a value before checking the contact details fields, (dp1 OR dp2) but even though using ( || ) the validation is acting as &&.
$('#send').click(function(){
if( document.downloadForm.SoftwareDp.value == "0" || document.downloadForm.ManualDp.value == "0" )
{
alert( "Please Select a file for Download" );
return false; }
// First check if Dropdown 1 OR dropdown 2 have been selected ( ONE at least)
if( document.downloadForm.name.value == "" && document.downloadForm.email.value == "" )
{
alert( "Please enter your details" );
return false; }
// then check if name and email are typed in.
else{ // run some ajax if above conditions are met } });
Demo : http://jsbin.com/UGotAFIL/1/edit?html,js,output
Thanks
Your condition working perfectly.
If you want to check both drop down are not selected you should use && instead of ||.
If you need to select at least one drop down means you can you can use
$('#send').click(function(){
if(!( document.downloadForm.SoftwareDp.value != "0" || document.downloadForm.ManualDp.value != "0" ))
{
alert( "Please Select a file for Download" );
return false; }
// First check if Dropdown 1 OR dropdown 2 have been selected ( ONE at least)
if( document.downloadForm.name.value === "" && document.downloadForm.email.value === "" )
{
alert( "Please enter your details" );
return false; }
// then check if name and email are typed in.
else{ // run some ajax if above conditions are met
} });
see this jsbin demo
If I understand you correctly, you want to show the error when no dropdown has a value, that is both have no value.
Change
if( document.downloadForm.SoftwareDp.value == "0" || document.downloadForm.ManualDp.value == "0" )
to either
if( document.downloadForm.SoftwareDp.value == "0" && document.downloadForm.ManualDp.value == "0" ) // both have the default value 0
or
if(!( document.downloadForm.SoftwareDp.value != "0" || document.downloadForm.ManualDp.value != "0" )) // none of them has not the default value
The way you are checking will always give alert unless you select other than 0 values in both.
You should do it this way:
if( document.downloadForm.SoftwareDp.value == "0" && document.downloadForm.ManualDp.value == "0" )
The above will give alert only when both are selected for 0. If one of them has other value it won't display alert.

Adding an if statement inside if statement

I have a function for a button which submits a form. This function checks to see if the 5 checkboxes are selected #co1,#co2,#co3,#div1,#cc1.
It then also checks to see if tcaccept select is set to 1.
If so the form submits, else the alert pops up.
This is the code i have at the moment:
$('#submit2pd').click(function(event) {
var $finishBoxes = $('#co1,#co2,#co3,#div1,#cc1');
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' )) {
alert('Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College');
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
All works brilliantly, but i want to add to this line as i have another option that is required. But this needs to be an if statement.
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length && $('#tcaccept').val() == '1' && THE IF STATEMENT))
this is what i need to incorporate into the if statement above.
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank
}
Any help would be greatly appreciated.
How about:
if (!($finishBoxes.length == $finishBoxes.filter(':checked').length &&
$('#tcaccept').val() == '1' &&
!($("#ctl").val() == "1" && $('#ctlapp').val() === "")))
What we're adding here is another condition which says, "And make sure it's not the case that #ctl is 1, and #ctlapp is blank".
Edit: and please see my comment above - your question is not about jQuery, forms, or validation. It's barely about JS.
if($('#tcaccept').val() == '1' && validate()) {
// do something
}
var validate = function(){
if ($("#ctl").val() == "1") {
$('#ctlapp') must not be blank
return false;
}
else if ($("#ctl").val() == "0") {
$('#ctlapp') can be blank;
return true;
}
return true;
}
I'd say clean up the code a little, and things will get a bit simpler:
$('#submit2pd').click(function(event) {
var fail_message = 'Please complete the Induction Checklist confirming that you have read and understood the Colleges main policies and procedures, agreeing to comply with these in line with the terms of your contract with the College',
$finishBoxes = $('#co1,#co2,#co3,#div1,#cc1'),
$checkedBoxes = $finishBoxes.filter(':checked'),
tcaccept = $('#tcaccept').val(),
ctl = $("#ctl").val(),
ctlapp = $('#ctlapp').val();
if (tcaccept == '1' && $finishBoxes.length != $checkedBoxes.length ) {
alert( fail_message );
return false;
} else if( ctl == "1" && ctlapp == "" ) {
alert( "some other message" );
return false;
}
// otherwise the form is submitted
window.location.href = "submit2pd.php";
});
I left the test for $('#ctl').val() == "0" out because it sounds like that's the only other value it can have, and there's no validation that needs to take place if it is "0".
Use a logic or || to capture both constalations:
$("#ctl").val() == "1" && $('#ctlapp') != ""
OR
$("#ctl").val() == "0"
if (
!(
$finishBoxes.length == $finishBoxes.filter(':checked').length
&&
$('#tcaccept').val() == '1'
&&
(
($("#ctl").val() == "1" && $('#ctlapp') != "")
||
$("#ctl").val() == "0"
)
)
)

Categories

Resources