Creating Datavalidation with custom Formula - javascript

I want to create DataValidation for a cell in google sheets with google app scripts, but i cannot find the syntax to create a custum formula for the validation.
My idea is to create a code to validate a time format HH:MM. For this matter i already have a a working Regexp (function CheckRegexp)
The only documentation i´ve found so far to this issue is this one: https://developers.google.com/apps-script/reference/spreadsheet/data-validation-criteria
function test() {
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getRange("E4");
var criteria = SpreadsheetApp.DataValidationCriteria.CUSTOM_FORMULA
//Custom formula CheckRegexp
var dv = SpreadsheetApp.newDataValidation().withCriteria(criteria, args).build();
cell.setDataValidation(dv);
}
function CheckRegexp(input) {
return /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/.test(input);
}
I want the result to be a Data Validation for my Regexp in a desire range.

It's not possible to set a custom formula(script-based) as a data validation criteria. Custom formula in this context(DataValidationCriteria.CUSTOM_FORMULA) refers to custom crafted formula by nesting inbuilt formulas.
Possible solution(s):
Use a edit trigger onEdit(e) to check each edit, whether it satifies a condition and clear the cell e.range.clear(), if not OR
Use inbuilt formula like this:
=REGEXMATCH(TO_TEXT(E4),"^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$")
To Read:
Event Objects
REGEXMATCH

Just another way for data validation is below:
=AND(ISDATE(E4), TEXT(E4, "hh:mm")=TO_TEXT(E4))
REGEXMATCH function is also suitable, but it may appear to be less readable for somebody.
By the way, both cases do not reject incorrect numerical input (I dont know why). They only mark cells as "Invalid: This cell's contents violate its validation rule".

It's too late, but might help someone still looking for it. Here's how you can set Custom Formula validation through script:
var range = SpreadsheetApp.getActive().getRange("A2");
var criteria = SpreadsheetApp.DataValidationCriteria.CUSTOM_FORMULA;
var args = ["=ISNUMBER(A2)"];
var val = SpreadsheetApp.newDataValidation().withCriteria(criteria,args);
val.setAllowInvalid(false);
val.setHelpText("Please enter valid number.");
range.setDataValidation(val);

Related

setFormula by using script in Google Sheets

I have a little knowledge of javascript I just want to know how to make a script that works in these scenario
I just want to set the second-row with D2:F2, or as long as the first row has a value to be a reference in the formula like in cells: D2={franco!F2:F}; E2={justin!F2:F}; F2 ={aeron!F2:F} and so on...
currently I am using the following codes:
function setFormula() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var rangeList = ss.getRange('d1:f1').getValue();
var range = ss.getRange('d2:f2');
range.setValue('={'+rangeList+'!F2:F}');
}
hope that someone can help me with this code. Thank you in advance
You want to put the formulas of {franco!F2:F}, {justin!F2:F} and {aeron!F2:F} to the cells "D2", "E2" and "F2", respectively.
In this case, you want to retrieve the values of franco, justin, aeron from the cells "D1:F1".
You want to achieve this using Google Apps Script.
I could understand like above. For this, how about this answer? Please think of this as just one of several possible answers.
Sample script:
function setFormula() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var rangeList = ss.getRange('d1:f1').getValues()[0];
var range = ss.getRange('d2:f2');
range.setFormulas([rangeList.map(function(e) {return '={'+e+'!F2:F}'})]);
}
At first, the values of franco, justin, aeron are retrieved. Using these values, each formula is creted in the loop with map
setFormulas uses the 2 dimensional array. Please be careful this.
References:
getRange()
getValues()
setFormulas()
map()

Problem with toLocaleDateString and Date.Prototype using MailMerge in Google Sheets

I'm Attempting to create a Merge between some sheet Data, a doc template and a final doc template.
Mainly, I have access to these files like this:
var contratotemplate = DocumentApp.openById(contratotemplateId);
var contratonovo = DocumentApp.openById(contratonovoId);
var ws = SpreadsheetApp.openById(planilhaId).getSheetByName("Contratos Ref Marca");
Than, used this code to pick each Data from a Range that I want.
var data = ws.getRange(3,1,1,ws.getLastColumn()).getValues();
The Problem is here when I try to replacetext with cell information from my sheet trough another function callback (the one that actually replace text with info):
data.forEach(function(r){
CriarMailMerge(
r[30].getDate()+"/"+r[30].getMonth()+"/"+r[30].getFullYear(),
paragrafosTemplate,
contratonovo);
});
The result is this:
11/5/2019 //in contratonovoId field supposed to have the correct date.
I've already tried .toLocaleDateString()
The result is:
June, 11 2019.
Which solves my problem, but I can't find a way to bring that info into Brazilian Portuguese.
Can u guys help me?
I Used this and worked:
r[30].getDate()+"/"+("0" + (r[30].getMonth() + 1)).slice(-2)+"/"+r[30].getFullYear(),
RESULT
11/06/2019

Spreadsheet script that checks if a cell is a number if not it clears the content, if it is a number clears the formatting

I'm not really good at this kind of things and googling didn't return any kind of results.
Does anyone know how a to write a script that clears all the cells in a specific column if they are not numbers? And if they are it just clears the formatting.
I would also like to apply the clear formatting part of the script for multiple cells that contain text. For these ones there is no need to check what the cells contain. I just want it to reset to plain text.(The default being 10, Arial)
So far this is all that I have
function onEdit()
{
var sheet = SpreadsheetApp.getActive().getSheetByName('Market');
var isNumber = sheet.getRange('E2:E1000').getValue()
if (isNumber
};
I do not know how the rest of the phrasing should look like. And I am mainly interested in the first part.
Thanks for the help!
This will remove the text. And if you want you can set the remaining numbers to text by removing the commented out script.
function onEdit(){
var sheet = SpreadsheetApp.getActive().getSheetByName('Market');
var lr=sheet.getLastRow()
var vals = sheet.getRange(2,5,lr,1).getValues()
var newVals=[]// New array of numbers only and blank where text.
for(i=0;i<vals.length;i++){
if(typeof vals[i][0]=="number"){//If a number keep the number.
newVals.push([vals[i][0]])}
else{ //If not a number create a blank value.
vals[i][0]=""
newVals.push([vals[i][0]])}
}
var set= sheet.getRange(2,5,newVals.length,1).setValues(newVals)//Reset column E.
// sheet.getRange(2,5,newVals.length,1).setNumberFormat('#STRING#')//If ypu want the numbers formated as a string remove //
Logger.log(newVals)
};

How to add IF/ELSE function in data validation in-cell dropdown function?

I'm trying to create an in-cell data validation drop down menu (in google spreadsheet) by using If/Else function.
Actually, I've 2 range of lists from which I only want to show one decided by a variable cell.
It sounds like this: If A1 is ABC then show range 1 in-cell dropdown & if A1 is XYZ then show range 2 in-cell dropdown.
Here's the code. Let me know what I'm doing wrong.
function dataval (){
var cell = SpreadsheetApp.getActive().getRange('B12');
if (cell=="Price") {
var cell = SpreadsheetApp.getActive().getRange('C12');
var range = SpreadsheetApp.getActive().getRange('D12:D19');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(range).build();
cell.setDataValidation(rule);
};
if (cell=="Technical") {
var cell = SpreadsheetApp.getActive().getRange('C12');
var range = SpreadsheetApp.getActive().getRange('E12:E19');
var rule = SpreadsheetApp.newDataValidation().requireValueInRange(range).build();
cell.setDataValidation(rule);
};
};
P.S.: I'm new to coding & this is my first ever ever post on SOF.
A problem with your code is the comparison cell=="Price". The variable cell is an object of class Range, not a string. To get the value it contains, you need cell.getValue(), so the comparison would be cell.getValue() == "Price".
You should also handle the event of the content of B12 changing. A simple way is to put the data validation code in onEdit trigger, and check whether the edit was to B12: e.g.,
if (e.range.getA1Notation() == 'B12') {
// change data validation
}
If the goal was simply to have a rule that forces inputs to be in one of two ranges, depending on another cell, that can be done without a script, using a custom formula with if and index. But that wouldn't provide a dropdown of values.

Type Casting in Apps Script

First time on StackOverFlow!
I am working on building an app that takes in a value through a UI Form TextBox. Once that form is submitted it calls a method that then appends a "/" to the value. The problem is that .append() is not available, because getElementById() returns a GenericWidget object and thus cannot be operated on as if it were a string. I have tried type casting it use .toString() in the var userinput = app.getElementById('input').toString; call and afterward using userinput = userinput.toString.
I have been working with Apps Script for about a month and a few days now and I think that casting to a different type other than GenericWidget would be helpful for anyone who wants to modify a value in a type specific way after passing the value to another method.
I have also done a good bit of research trying to find a solutiong for my problem but like a couple times in the past working with Apps Script I find that since it is a younger language there isn't as much helpful information as there is with languages like Javascript, HTML, and XML. Any help is appreciated.
You have to get the textBox value using e.parameter.textBoxName an then re-assign a value to the textBox. A short example will be more explicit
function doGet(){
var app = UiApp.createApplication();
var textbox = app.createTextBox().setName('txt').setId('txt')
// add other elements, handlers, callBackElements, etc...
}
function changetext(e){
var app = UiApp.getActiveApplication();
var textBoxValue = e.parameter.txt ; // get the value in the text box
var txtBoxWidget = app.getElementById('txt') ; get the widget by its ID
txtBoxWidget.setText(textBoxValue+'/'):// assign the modified value
return app ;// update the UI with new value
}

Categories

Resources