Validate fields before allowing a PDF form to be submitted - javascript

I'm trying to create a PDF with a submit button that runs a custom JavaScript. The purpose of the code is to determine the value of one of the form fields and then run a math equation to determine if a warning should be displayed to the user or if they should be allowed to submit.
There are 3 scenarios I want to account for when the user clicks the submit button:
If the "CompletedValue" field is greater than or equal to 1,500,000 and the equation returns a value of less than 40. If this is true, the form should generate error message 1.
If the "CompletedValue" field is less than 1,500,000 and the equation returns a value of less than 25. If this is true, the form should generate error message 2.
Scenario 1 & 2 are false. If this is true, the form should generate an email.
To accomplish this I've written the following code, however, it is not working. When I click the Submit button, nothing happens.
var cV = this.getfield("CompletedValue").value;
var nV = cV - this.getfield("PresentValue").value;
var percentage = ( nV / cV ) * 100;
if (cV >= 1500000 && percentage < 40)
{
var error1= app.alert(errorMessage1,0,0,cTitle);
}
else if (cV < 1500000 && percentage < 25)
{
var error2= app.alert(errorMessage2,0,0,cTitle);
}
else
{
this.mailDoc({bUI: true, cTo: cToAddr, cSubject: cSubLine, cMsg: cBody});
}
Any help on getting this to work would be appreciated.

I resolved this issue simply by changing the case in the first two statements.
The case I used originally was:
var cV = this.getfield("CompletedValue").value;
This was corrected to:
var cV = this.getField("CompletedValue").value;
Note the capital 'F' in the getField.

Related

Variables in display form not picking up latest values after edit in SharePoint/jQuery

I'm currently converting Yes/No values in display form from the checkboxes in new form. First round of display form I managed to convert the values but when I edit the form in Edit form, it still display the old values.
For example:
New form: Field A = Yes (Boolean Yes/No)
Display form: Field A = 1 (Converted)
Edit form: Field A = No
Display form: Field A = 1 (Expectation to display 0 instead 1)
Sample code
<script src="https://workspace.maybank.com.my/sites/sdlc/SiteAssets/jquery-1.10.0.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
var ValQ1_1 = $('td.ms-formlabel:contains("BAU Activities - URS, SR, IT initiatives, enhancements (Restricted to less than or equal to 20 IT Mandays)")').siblings(".ms-formbody").text()
var ValQ1_2 = $('td.ms-formlabel:contains("Production fixes - breakfix, remediation (compliance/audit/security), other than Incident Sev1/2, etc.")').siblings(".ms-formbody").text()
var ValQ1_3 = $('td.ms-formlabel:contains("Emergency or Urgent production fixes/change/RFC - with Incident Sev1/2 and/or ECAB")').siblings(".ms-formbody").text()
var ValQ1_4 = $('td.ms-formlabel:contains("Project - More than 20 IT man-days (per PMF - Project Management Framework)")').siblings(".ms-formbody").text()
var ValQ1_5 = $('td.ms-formlabel:contains("Project - Implementation of a new system/solution/application/infrastructure services")').siblings(".ms-formbody").text()
if (ValQ1_1= "Yes")
{
$('td.ms-formlabel:contains("BAU Activities - URS, SR, IT initiatives, enhancements (Restricted to less than or equal to 20 IT Mandays)")').siblings(".ms-formbody").text("1")
alert(ValQ1_1);
}
});
</script

Javascript check/validate that sum of three fields add up to 1

I'm creating a nutrition JavaScript calculator where the user enters a daily calorie intake and selects their percentage of carbohydrate, protein, and fat. The result is the percentage of calories and grams from each nutrient. I've got it working but...
As a math check/validation, I want to include some code that will add up the selected carbohydrate, protein, and fat percentages and ensure they equal exactly 1 (or 100%). If this is not true, then I want a little alert/error message to pop up so they know to go back and fix this before the "Calculate" button will work.
Here is the relevant code for what I'm trying to ensure adds up to 1
Thanks in advance for any advice you can provide.
I'm a relative novice with JS, so I'm not even really sure of the exact code I need to use in this case.
<script type="text/javascript">
function calc (form) {
var C, P, F
P=form.Protein.options[form.Protein.selectedIndex].value
F=form.Fat.options[form.Fat.selectedIndex].value
C=form.Carbohydrate.options[form.Carbohydrate.selectedIndex].value
}
</script>
function calc(form) {
const errorEl = document.getElementById('error');
// Clear the error before calculating the new value.
errorEl.innerText = 'Your error message';
const protein = form.Protein.options[form.Protein.selectedIndex].value;
const fat = form.Fat.options[form.Fat.selectedIndex].value;
const carbohydrate = form.Carbohydrate.options[form.Carbohydrate.selectedIndex].value;
if (Number.isNaN(prtein) || Number.isNaN(fat) || Number.isNaN(carbohydrate)) {
document.getElementById('error').innerText = 'Your error message';
return;
}
const sum = parseFloat(protein) + parseFloat(fat) + parseFloat(carbohydrate);
if (sum > 1) {
document.getElementById('error').innerText = 'Your error message';
}
}
And you also need an element with the error id in your form that will show the error message. For example <p id="error"></p>

Partial Password Masking on Input Field

So I need to mask a SSN# input field, lets say the ssn is 123-45-6789, I need to display ***-**-6789 (real time as they enter each digit) but I still need to retain the original value to submit.
I got to the point where I can do that if the user strictly enters the value but it breaks if the user does anything else such as delete, or moving cursor to a random position and adds/deletes a number, copy pasting/deleting, etc. I really don't want to listen to a bunch of events to make this work if thats even possible.
I also tried having a div sit on top of the input field to display the masked ssn while the actual ssn was transparent/hidden behind it but again they lose the functionality of being able to add/delete/select delete/paste in random parts (other then when they start at the end) and also the cursor not totally in sync with the end of the ssn number (asterisk size was the issue). This also broke on some mobile browsers.
I also thought of having two separate input fields, one type password, and one type text sit right next to each other, but again highlighting and deleting/pasting between the two would be an issue.
Ideally if there was something out there to have an input field have two types, part of the value be type password and the rest be type text, that would be fantastic. Btw this is for react js app.
TLDR: Need a fully functional input field that will do password masking on only first 5 digits of ssn and be plaintext for last 4 digits (while having the full plaintext value available for submission).
Thanks!
This might be a little sloppy, but it works as you want it to, is all in one text field, returns the full accurate SSN (despite replacing first 5 values with bullet points), and allows for editing anywhere in the field.
<input type="password" id="ssn" maxlength=9 />
<script>
var ssn = document.getElementById('ssn');
ssn.addEventListener('input', ssnMask, false);
var ssnFirstFive = "";
var secondHalf = "";
var fullSSN = "";
function ssnMask(){
if (ssn.value.length <= 5){
ssn.type = 'password';
}
else{
detectChanges();
secondHalf = ssn.value.substring(5);
ssn.type = 'text';
ssn.value = "•••••";
ssn.value += secondHalf;
fullSSN = ssnFirstFive + secondHalf;
}
}
function detectChanges() {
for (var i = 0; i < 5; i++){
if (ssn.value[i] != "•"){
ssnFirstFive = ssnFirstFive.substring(0, i) + ssn.value[i] + ssnFirstFive.substring(i+1);
}
}
}
</script>
Essentially, every time the input is changed, it checks to see if it matches the first 5 from before, and if it doesn't, it will update the necessary characters.
You can use 3 different fields and make then password fields.
Add a focus handler that changes their type into text and a blur handler that changes them back to password.
You can combine them before submission or on the server.
#ssn1{width:25px;}
#ssn2{width:20px;}
#ssn3{width:35px;}
<input type="password" name="ssn" maxlength=3 id="ssn1" />
<input type="password" name="ssn" maxlength=2 id="ssn2"/>
<input type="password" name="ssn" maxlength=4 id="ssn3"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('[name="ssn"]').focus(function() {
$(this).attr("type", "text")
});
$('[name="ssn"]').blur(function() {
$(this).attr("type", "password")
});
</script>
You can also write a pass handler to all a full SSN to be pasted in the first field and have all three fields get set.
This is the closest you are going unless you work with a single full text box and give the user the ability to mask and unmask the field.
In production apps, this actually the approach I take:
Masked:
Unmasked:
You can implement you own focus/blur functions to automatically unmask/mask the field as needed.
Achieve this using html data attributes.
i have used the same html tag and store actual value in html tag attribute (data-value) to use later on and store value to display in html tag attribute value.
Function to partial mask input value
function mask_field_value(obj, mask_letters_count=7){
mask_value = $(this).data('mask-value') || '';
unmask_value = $(this).data('unmask-value') || '';
if (obj.value.length <= mask_letters_count){
obj.type = 'password';
mask_value = obj.value;
$(this).data('mask-value', obj.value);
} else {
obj.type = 'text';
unmask_value = obj.value.substring(mask_letters_count);
obj.value = "*".repeat(mask_letters_count) + unmask_value;
$(this).data('unmask-value', unmask_value);
}
$(this).data('value', mask_value + unmask_value);
console.log($(this).data('value'));
}
Add an event on input fields to mask
$(document).ready(function () {
$(document).on('keyup', '.mask_input_display', function () {
mask_field_value(this);
});
});

javascript regex validation if no content

I have the following validation on a form field:
$(".controlsphone input").blur(function() {
var ree = /^\d+$/;
if(ree.test(document.getElementById("register_telephone").value))
{
$(this).css('border-color','green');
$(this).siblings('.info').css('display','none');
$(this).siblings('.error').css('display','none');
$(this).siblings('.valid').css('display','inline-block');
$("#email_error401112").hide();
$('#registerErrors').hide();
}
else
{
$('#registerErrors').show();
$('#email_error401112').remove();
$('#registerErrors').append('<p id="email_error401112">Please enter a phone number</p>');
}
});
I would like to only validate the field if a number exists. The field is not required, but if there is content within the field, it needs to be valid (a number)
How does the above code look? Any ideas what i can do to implement this?
Cheers, Dan
Use
var ree = /^\d*$/;
because + stands for one or more, excluding zero.
while * stands for zero or more

Can't access ExtJS radio button on form

So I have an .aspx page. In this grid I'm adding a bunch of controls. The first control however is an ExtObject, not one of our preset VB.NET controls. When I go to access the value on the backend for this field with this code:
form.AndOr.getValue()
It doesn't work. I really have no idea what is wrong. Basically, the radio button value isn't saving when I save the rest of the stuff. So I tried to add code to do it. It was just defaulted to 'And' each time. Below is a snippet of code from the actual asp.net grid. Any ideas?
With .Item(2)
.Ref = "../Payee2"
.LabelWidth = 90
With .AddFieldSet("Payee 2")
.AddControl(New Forms.Control("", "../PayeeId")).Hidden = True
.AddControl(New Forms.Control("", "../AddressId")).Hidden = True
.AddExtObject("{xtype:'radiogroup', ref:'../AndOr', defaults:{name:'rdo-payee2'}, width:120, items:[{boxLabel:'And', checked:true, inputValue:'and'},{boxLabel:'Or', inputValue:'or'}]}")
Dim ddlPayee2 As New Controls.ComboBox("", "../PayeePreInfo2", "Payee")
With ddlPayee2
.ForceSelection = True
.TypeAhead = False
.EmptyText = "Select Payee Details"
.ValueField = "AddressId"
.XTemplate = "applicantTemplate"
.ClientStore = "applicantAddressStore"
.AddListener(Akcelerant.Framework.WebControls.Controls.EventType.Select, "function(){prefillPayee('PAYEE2');}")
End With
.AddControl(ddlPayee2)
With .AddControl(New Forms.Control("", "../FirstName", "First Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10483, True)
End With
With .AddControl(New Forms.Control("", "../LastName", "Last Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10484, True)
End With
The error it throws is this:
Stack overflow at line: 16736
edit:
reverted some changes back and everything saves EXCEPT that value into the DB.
go to add this line to the javascript save function
if (form.AndOr.getValue() == 'and') {
payeeRec.set('IsPayee2RequiredToSign', 1);
} else {
payeeRec.set('IsPayee2RequiredToSign', 0);
}
and i get this error:
form.AndOr is not defined
Does the Ext ref: mean something different than my controls and how I access them?
Added a ref to the item of checkWin.
Then the ref to the radio value became
checkWin.Payee2.AndOr.getValue()
With that it can recognize the control on the form.

Categories

Resources