Validate semi colon separated e-mail with Zod resolver and react-hook-form - react-hook-form

I need to validate semi colon separated e-mails but the below validation does not work and I cannot use .regex. I believe .refine should be able to do this but I can't find a good way to do it.
const customSchema = z.object({
factoryEmail: z.
.string()
.email()
});
I've tried the following
const customSchema = z.object({
factoryEmail: z.
.string()
.email()
.refine((emailValue) => emailValue.split(';').map(function(item) {
customSchema.parse(item)
});
The above does not work. What would I need to do in .refine to be able to validate semicolon separated e-mails, for example
playerone#gmail.com, playertwo#gmail.com.

const customSchema = z.object({
factoryEmail: z
.string()
.refine((emailValue) => emailValue.split(";").every((item) => z.string().email().safeParse(item).success)),
});
This validates that the string is emails, separated by a semicolon ;.
const a = customSchema.safeParse({
factoryEmail: "foo#example.com",
}).success;
const b = customSchema.safeParse({
factoryEmail: "foo#example.com;banana#example.com",
}).success;
const c = customSchema.safeParse({
factoryEmail: "foo#example.com,banana#example.com",
}).success;
console.log(a, b, c);
This outputs true true false.

Related

Lua unusual variable name (question mark variable)

I have stumbled upon this line of code and I am not sure what the [ ? ] part represents (my guess is it's a sort of a wildcard but I searched it for a while and couldn't find anything):
['?'] = function() return is_canadian and "eh" or "" end
I understand that RHS is a functional ternary operator. I am curious about the LHS and what it actually is.
Edit: reference (2nd example):
http://lua-users.org/wiki/SwitchStatement
Actually, it is quite simple.
local t = {
a = "aah",
b = "bee",
c = "see",
It maps each letter to a sound pronunciation. Here, a need to be pronounced aah and b need to be pronounced bee and so on. Some letters have a different pronunciation if in american english or canadian english. So not every letter can be mapped to a single sound.
z = function() return is_canadian and "zed" or "zee" end,
['?'] = function() return is_canadian and "eh" or "" end
In the mapping, the letter z and the letter ? have a different prononciation in american english or canadian english. When the program will try to get the prononciation of '?', it will calls a function to check whether the user want to use canadian english or another english and the function will returns either zed or zee.
Finally, the 2 following notations have the same meaning:
local t1 = {
a = "aah",
b = "bee",
["?"] = "bee"
}
local t2 = {
["a"] = "aah",
["b"] = "bee",
["?"] = "bee"
}
If you look closely at the code linked in the question, you'll see that this line is part of a table constructor (the part inside {}). It is not a full statement on its own. As mentioned in the comments, it would be a syntax error outside of a table constructor. ['?'] is simply a string key.
The other posts alreay explained what that code does, so let me explain why it needs to be written that way.
['?'] = function() return is_canadian and "eh" or "" end is embedded in {}
It is part of a table constructor and assigns a function value to the string key '?'
local tbl = {a = 1} is syntactic sugar for local tbl = {['a'] = 1} or
local tbl = {}
tbl['a'] = 1
String keys that allow that convenient syntax must follow Lua's lexical conventions and hence may only contain letters, digits and underscore. They must not start with a digit.
So local a = {? = 1} is not possible. It will cause a syntax error unexpected symbol near '?' Therefor you have to explicitly provide a string value in square brackets as in local a = {['?'] = 1}
they gave each table element its own line
local a = {
1,
2,
3
}
This greatly improves readability for long table elements or very long tables and allows you maintain a maximum line length.
You'll agree that
local tbl = {
z = function() return is_canadian and "zed" or "zee" end,
['?'] = function() return is_canadian and "eh" or "" end
}
looks a lot cleaner than
local tbl = {z = function() return is_canadian and "zed" or "zee" end,['?'] = function() return is_canadian and "eh" or "" end}

Currency formate REGEXP, change symbol

I am working with HighChart and I need to format a currency value in a specific format.
Example -> XX.XXX.XXX, XX €
I am using this function in highchart to format the value correctly:
formatter: function () {
return parseFloat (this.total, 10) .toFixed (2) .replace (/ (\ d) (? = (\ d {3}) + \.) / g, '$ 1,'). toString () + ' € ';
}
The problem is that I am not getting the points and commas to match as I intend.
Example for values:
Given -> 1052325
Expected -> 10.523,25 €
Current value obtained -> 10,523.25
I could do a new replace() and change the commas for the points, but I would like to know how to do it right away at REGEXP.
Thank you very much
Ok. I cant use some of the functions in HighChart.
I try this code in the ppotaczek example
Highcharts.chart('container', {
series: [{
data: [1052325],
dataLabels: {
enabled: true,
formatter: function() {
var originalString = parseFloat(this.y, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$ 1,').toString();
var finalPriceString = originalString.split('');
var finalPriceStringLenght = finalPriceString.length;
var rowtoChange = finalPriceStringLenght - 3;
finalPriceString[rowtoChange] = 'I';
var lastString = finalPriceString.join('') + ' €';
alert(lastString);
}
}
}]
});
The code works in the Fiddle example, but it doesn't work when I put it in the Highchart Json.
I tried another approach now, I always have this string format so I just want to replace the third character from the end of the string.
For this I am using this replace with regexp:
stringFormated.replace(/.$/,',');
It works and replaces well. The problem is that it is always at the last character of the string. I wanted it to go to the third character after the end of the string.
Best regards

Different output from encodeURIComponent vs URLSearchParams

I built an oauth2 url with query params using URLSearchParmas API. However, the output URL didn't return an expected url. Can anyone help me understand the difference between those two APIs and how can I get the same result as the output of encodeURIComponent, using URLSearchParams? Thanks!
const expected = encodeURIComponent('code id_token'); // code%20id_token
const search = new URLSearchParams();
search.set('response_type', 'code id_token');
search.toString(); // code+id_token
According to WHATWG, URLSearchParams uses application/x-www-form-urlencoded format. While it's suitable for decoding URL queries, for encoding it can lead to unexpected results such as spaces being encoded as + and extra characters such as ~ being percent-encoded. It's better to use encodeURIComponent instead:
Having an object:
const params = {
text1: 'aaa bbb',
text2: '-._*~()'
}
Instead of:
url.search = (new URLSearchParams(params)).toString()
Use:
url.search = Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&')
Also, according to MDN even encodeURIComponent doesn't conform to newer RFC 3986 which defines more characters to escape, for example *. While it's probably safe not to escape these additional characters if you aren't using them as field separators, if you want to be strictly conformant to latest RFC, use this updated implementation from MDN:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase();
});
}
A playground for experimenting:
const params = {
text1: 'aaa bbb',
text2: '-._*~()'
}
const url1 = new URL('http://example.com')
const search1 = new URLSearchParams(params)
url1.search = search1 // Incorrect
console.log('URLSearchParams', url1.toString())
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
const url2 = new URL('http://example.com')
const search2 = Object
.entries(params)
.map(([key, value]) => `${fixedEncodeURIComponent(key)}=${fixedEncodeURIComponent(value)}`)
.join('&')
url2.search = search2 // Correct
console.log('fixedEncodeURIComponent', url2.toString())

Split string into list of words and separators

Given this string:
one#two*three#four#five*
What is a fast solution to extract the list of Pairs?
Each pair contains the word with its separator character like this:
[
['one', '#'],
['two', '*'],
['three', '#'],
['four', '#'],
['five', '*']
]
Specifically in my case I want to use both white space and new line characters as separators.
You'd need a regular expression:
(\w+)([#|*])
See example Dart code here that should get you going: https://dartpad.dartlang.org/ae3897b2221a94b5a4c9e6929bebcfce
Full disclosure: dart is a relatively new language to me.
That said, regex might be your best bet. Assuming you are only working with lowercase a-z letters followed by a single character, this should do the trick.
RegExp r = RegExp("([a-z]+)(.)");
var matches = r.allMatches("one#two*three#four#five*");
List<dynamic> l = [];
matches.toList().asMap().forEach((i, m) => l.add([m.group(1), m.group(2)]));
print(l);
Based on other responses here's my solution for white spaces and new lines as separators:
void main() {
RegExp r = RegExp(r"(\S+)([\s]+|$)");
var text = 'one two three \n\n four ';
var matches = r.allMatches(text);
List<dynamic> l = [];
matches.toList().asMap().forEach((i, m) => l.add([m.group(1), m.group(2)]));
print(l);
}
Output
[[one, ], [two, ], [three,
], [four, ]]
Explanation: https://regex101.com/r/cRpMVq/2

When is const optional in Dart 2?

In Dart Object() constructor is declared as const so:
identical(const Object(), const Object()); //true
I know that in Dart 2 the keyword const is optional and I thought that the previous statement was equivalent to:
identical(Object(), Object()); //false
But actually it seems to be equivalent to:
identical(new Object(), new Object()); //false
Now my doubts are:
1) When is const keyword optional?
2) Is there any way to ensure instances of my classes to be always constant without const keyword? So that I can obtain:
indentical(MyClass(), MyClass()); //true (is it possible?)
Dart 2 allows you to omit new everywhere. Anywhere you used to write new, you can now omit it.
Dart 2 also allows you to omit const in positions where it's implied by the context. Those positions are:
Inside a const object creations, map or list literal (const [1, [2, 3]]).
Inside a const object creation in metadata (#Foo(Bar()))
In the initializer expression of a const variable (const x = [1];).
In a switch case expression (case Foo(2):...).
There are two other locations where the language requires constant expressions, but which are not automatically made constant (for various reasons):
Optional parameter default values
initializer expressions of final fields in classes with const constructors
1 is not made const because we want to keep the option of making those expressions not need to be const in the future. 2 is because it's a non-local constraint - there is nothing around the expression that signifies that it must be const, so it's too easy to, e.g., remove the const from the constructor without noticing that it changes the behavior of the field initializer.
const is optional in a const context. Basically a const context is created when the expression has to be const to avoid compilation error.
In the following snippet you can see some place where const is optional:
class A {
const A(o);
}
main(){
// parameters of const constructors have to be const
var a = const A(const A());
var a = const A(A());
// using const to create local variable
const b = const A();
const b = A();
// elements of const lists have to be const
var c = const [const A()];
var c = const [A()];
// elements of const maps have to be const
var d = const {'a': const A()};
var d = const {'a': A()};
}
// metadatas are const
#A(const A())
#A(A())
class B {}
You can find more details in Optional new/const and Implicit Creation.

Resources