Is it possible to add something to this function that will set up the date format and require the user to enter MM/DD/YYYY? MASK is not working..
Fee Calculator Function:
function getDatePrice() {
var datePrice = 0;
var theForm = document.forms.form;
var purchasedate = theForm.elements.purchasedate;
var date = new Date(purchasedate.value);
if (Object.prototype.toString.call(date) !== '[object Date]') {
date = new Date();
}
var today = new Date();
var diffMilli = today - date;
var diffDays = Math.floor(diffMilli / 1000 / 60 / 60 / 24); // ..Divide!
if (diffDays > 30) {
datePrice = 20;
}
else {
datePrice= 0;
}
return datePrice;
}
Calling Function:
function calculateTotal()
{
var titleFees = getDatePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Estimated Transfer Fees $"+titleFees;
}
Input Button: (Requiring ColdFusion):
<cfinput
type="datefield"
name="purchasedate"
width="130"
required="yes"
message="Please enter purchase date."
value="#dateformat(now(),"mm/dd/yyyy")#"
oninput="calculateTotal();"
>
I am going to go ahead and add an answer here since another question has been opened regarding the same issue. I believe the problem is that the mask attribute on the <cfinput type="datefield" ... code only works when using Flash forms - documentation reference.
I have emphasized the text from that documentation below:
Masking cfcalendar and datefield input
In the cfcalendar tag and the Flash format datefield input control, you use the following masks to determine the format of the output. You can use uppercase or lowercase characters in the mask:
...
The following pattern specifies that the Flash form sends the date selected using a datefield input control to ColdFusion as text in the format 04/29/2004:
<cfinput name="startDate" type="datefield" label="date:" mask="mm/dd/yyyy"/>
Since you are not using a Flash form the mask is not working for you. You could try switching to a regular <cfinput type="text" ... input and change your mask to something like "99/99/9999". That would give you the correct format but the user could still enter invalid dates so you would need additional code to catch that.
In the comments you stated:
What is strange is that I have others that actually work like.. <cfinput type="text" name="odate" id="odate" validateat="onSubmit" validate="noblanks" required="yes" message="Please enter odometer date." value="" mask="99/99/9999" placeholder="08/05/2014"> but for some reason it is just the datefield that will not except the MASK
Notice that you are using a "text" input here so the mask works (as in my previous comment). It is only with the "datefield" type that the mask does not work; unless you are using a Flash form.
This is just another example of why using the built-in ColdFusion UI tags is not a good idea. They work for very simple examples but when you need more customization they fail you. You would be better off to use a JavaScript library (like jQuery) for client side validation. Adobe's own Ben Forta acknowledged this several years ago. And the ColdFusion-UI-the-Right-Way project was started because of this as well.
EDIT
Adam pointed out another reference in the ColdFusion documentation that reinforces my point. I have emphasized the text from that documentation below:
Masking input data
In HTML and Flash forms, the mask attribute controls the format of data that can be entered into a text field or that is selected in a datefield input control calendar. In HTML format, it does not prevent users from typing a date that does not follow the mask into a datefield input control. You can combine masking and validation on a field.
Related
I believe it this worked on mobile devices at one point but now its not working.
MainDate is a calendar date elected by the user using a formatted text box, and the bottom code was implemented individually in separate text box's (sun-sat) which used the below to calculate the date. I incremented the number 0 from "Add days to date" in each text box to get the correct date.
// Custom Calculate script for MainDate field
(function () {
// Get date entered into the MainDate field
var sDate = getField("MainDate").valueAsString;
// Convert string to date
var d = util.scand("mm/dd/yy", sDate);
// Add days to date
d.setDate(d.getDate() - 0);
// Populate this field with the result
if (sDate) {
event.value = util.printd("mm/dd/yy", d);
} else {
event.value = "";
}
})();
Again I believe at one point it did work on mobile devices or I might be completely wrong. Is there a fix or another method to use to be able to calculate the date via mobile devices?
Update: I tested qPDF Viewer, Xodo, foxit and a few other unknown editors and no luck on the Android side....
revised code:
// Custom Calculate script for MainDate field
(function () {
var MDate = getField("MainDate").value;
// Get date entered into the MainDate field
var sDate = MDate;
// Convert string to date
var d = util.scand("mm/dd/yy", sDate);
// Add days to date
d.setDate(d.getDate() - 6);
// Populate this field with the result
if (sDate) {
event.value = util.printd("mm/dd/yy", d);
} else {
event.value = "";
}
})();
This now works with the Foxit android app but not in Xodo nor Adobe... Thanks!
Speaking just for the Adobe mobile viewers, I've never known Field.valueAsString to be supported. Only Field.value is supported. You also might want to prefix getField() with "this." – joelgeraci
The fix works on Foxit and unsure of what apps for iOS...
I am currently writing a custom function in Google App Scripts. Right now I am struggling. I defined an argument to take input from a date cell and change the format.
e.g 9/16/2010 to 09.16.2010 where a given column has the former date and the function outputs the latter.
The output is a string, but I can't seem to find any information on this specific text editing feature of javascript.
It's also worth mentioning that the date in a given column is based on a form output, I am not calling a specific short date in the code, so rather this is more string manipulation than date formatting
Any help is appreciated.
/**
*Generates a Trip Key
*
*#param DateColumn Date
*#param SchoolColumn School name
*#param LocationColumn Location
*#customfunction
*/
function GENERATEKEY(DateColumn) {
var Date = DateColumn
const dateStr = Date;
const dateArr = dateStr.split('/');
dateArr[0] = ('0' + dateArr[0]).slice(-2);
dateArr[1] = ('0' + dateArr[1]).slice(-2);
const DateEdited = dateArr.join('.');
return neWDateStr; //gives 00.00.0000
//var Key = Date SchoolColumn "#" LocationColumn
}
Date is a built-in object. It should not be used as a variable name.
While const is allowed in Google Apps Script, it's not fully supported (it doesn't work as the ECMAScript states). IMHO it's better to use var to avoid "confusions".
In Google Sheets, based in the spreadsheet settings, change values entered in supported date-time format into serial numbers and use a number format to display it as date, time, date-time or duration. When a serial number displayed as date, date-time, time or duration is passed to a custom function, Google Apps Script convert it to a Date object.
To return a date formatted use Utilities.formatDate(...) Details in https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate,-timezone,-format
Related
How to format the date in this Google Apps Script
You could simply use inbuilt TEXT function:
=TEXT(A2,"mm.dd.yyyy")
The reason your current script(as provided in one of the previous answers) doesn't work is because the argument DateColumn is not of type String. You can convert the date object to a specific string and format it accordingly or use inbuilt Utilities library.
function DOWHATTEXTDOES(dateColumn) {
return Utilities.formatDate(dateColumn, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy.MM.dd")
}
Essential Reading:
Custom function Data type
Date
You can do something like this
"02/05/2009".split('/').join('.');
Get and Set the numberFormat for the active range
Sheet.getRange().setNumberFormat("mm.dd.yyyy");
Here's a dialog and function that I use sometimes for playing around with different formats. I find it a lot easier and quicker that using the spreadsheet functions.
The top function is a dialog that reads and displays the current format for the active range and has a textbox and button for each cell in the in the active range that allows you to set the number format and see the change immediately.
function getandSetActiveRangeFormats() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var rg=sh.getActiveRange();
var fA=rg.getNumberFormats();
var html='<style>th,td{border:1px solid black;}</style><table><tr><th>Item</th><th>A1 Notation</th><th>Number Format</th><th>Enter Format</th><th>Set Format</th></tr>';
var item=1;
var row=rg.getRow();
var col=rg.getColumn();
fA.forEach(function(r,i){
r.forEach(function(c,j){
var txt=Utilities.formatString('<input type="text" id="RC-%s-%s" />',row+i,col+j);
var btn=Utilities.formatString('<input type="button" value="Set Form" onClick="setFormat(%s,%s);" />',row+i,col+j);
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',item++,sh.getRange(row + i,col + j).getA1Notation(),fA[i][j],txt,btn);
});
});
html+='</table><input type="button" value="Exit" onClick="google.script.host.close();" />';
html+='<script>function setFormat(row,col){var f=document.getElementById("RC-"+row+"-"+col).value;google.script.run.setFormat(row,col,f);}</script>';
var ui=HtmlService.createHtmlOutput(Utilities.formatString(html));
SpreadsheetApp.getUi().showModelessDialog(ui, "Display Cell Formats")
}
function setFormat(row,col,format) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
sh.getRange(row,col).setNumberFormat(format);
}
Animation:
Validate inline edit on a saved search, suitescript 1.0
I have the validation working for non-inline edits when the change is made on the record itself. I am looking to get the same validation online when an edit is made on the saved search as an inline edit. I have 3 date fields, a ship, cancel, and expected date. The cancel date needs to be between the ship date and the expected date. I am using the following code. TNHelper.inRageDateCheck just returns true if the 3rd date is between the first two dates.
Edit Example
function saveRecord_Functions() {
var noProblem = true, alertmsg = '';
// EXPECTED DATE Required only in Form "TN Purchase Order"
if (nlapiGetFieldValue('customform') != 102 || type != 'xedit') return true;
var helper = new TNHelper();
if (helper.inRageDateCheck(nlapiGetFieldValue('custbody_startshipdate')
,nlapiGetFieldValue('custbody_tn_po_expecteddate')
,nlapiGetFieldValue('custbody_tn_po_canceldate'))){
noProblem = true;
}else{
alertmsg = 'Cancel Date must be between Start Ship Date and Expected Date.';
}
if(alertmsg.length>0){
alert(alertmsg);
return;
}
return noProblem;
}
I would like it to pop alertmsg when an invalid cancel date is put into the field and attempted to be saved.
This will not work on the client script save record entry point; the xedit context validation is only available for user event scripts. You can add validation with a UE script, but unfortunately you will not be able to send an alert to the user via alert(). For more information on how to do this, check out this question: Validate In-Line Edits in Netsuite
I have mask for my date in MM/YY format. There must be month >= then current, and year >= then current year.
I have regexp pattern here:
<input id="expiration" type="tel" placeholder="MM/YY" class="masked" pattern="(1[0-2]|0[1-9])\/(1[8-9]|2\d)" data-valid-example="12/18" onchange="onChangeInput(event)"/>
Seems like it's ok for this format, but I still can write a year less than 18.
Need a little help from you, stack overflow.
The pattern seems fine, however as noted using an input type tel is likely not a good idea as it's semantically inconsistent.
You might try using script instead of relying on browser validation as support is patchy. Something like the following may suit.
function validateInput(evt) {
var re = new RegExp(this.pattern);
var s = this.value;
// Show whether value is valid or not when input is full
document.querySelector('#s0').textContent = s.length < 5 || re.test(s)? '' : 'Invalid';
}
window.onload = function(){
document.querySelector('#i0').addEventListener('input',validateInput, false);
};
<input id="i0" type="text" placeholder="MM/YY" pattern="(1[0-2]|0[1-9])\/(1[8-9]|2\d)" maxlength="5"><br>
<span id="s0"></span>
I have been reading the parsley.js docs and I have tried to write a custom validator to validate if a date is greater than todays date.
I have the conditional code written, but I am completly confused about how to apply the conditional error message.
I have completed the task with a parsley maxlength validator, but realise that this is less than perfect.
How do I write the custom validation with parsley?
Here is my js/jq code that dynamically adds & deletes the validation using the maxlength:
if(formattedStartDate > todaysDate) {
$('#id_voluntary_start_date').attr('data-parsley-maxlength', '1');
$('#id_voluntary_start_date').attr('data-parsley-maxlength-message', '{% trans "Commencement Date must not be greater than today." %}');
$('#id_voluntary_start_date').parsley();
} else {
$('#id_voluntary_start_date').attr('data-parsley-maxlength', '50');
}
Any help with implementing the custom validation would be appreciated.
First of all set one hidden textbox and store today's date in it and just write below code on date field you want to check.
data-parsley-dlte = "#hiddentextboxid",
data-parsley-dlte_message = "Your custom message"
Don't forget to set parsley on the form in which you have your dom elements.
If this doesn't work check the version of parsley js.
Hope this is helpful.
All you need to do is register your custom validator either globally (in window.ParsleyConfig) or for your particular form as follows:
myForm.parsley({
validators: {
custom: function (value) {
var now = new Date();
var date = new Date(value);
return date < now;
}
},
messages: {
custom: 'Commencement Date must not be greater than today'
}
});
Here is jsFiddle with a sample