How to write Conditional regex? - reactjs

I want to use Yup for validation. in a part of validation I have
const validationSchema = Yup.object({password: Yup.string().matches(passwordRegex, "passRegex")})
passWordRegex is a varibale that contains a regex :
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{4,32}$/;
I have some booleans that determine that if for example small letter or big letter or speciall character is needed in password or not:
smallLetter = false
capitalLetter = true
specialChar = true
now my regex ( passwordRegex variable) is not conditional . how can I write a regex (passwordRegex variable) conditional base on my Boolean variables

You could build the regex string you want and then create a proper RegExp object:
var input = "aB#3";
var smallLetter = false;
var capitalLetter = true;
var specialChar = true;
var number = true;
var regex = "";
if (smallLetter) regex += "(?=.*[a-z])";
if (capitalLetter) regex += "(?=.*[A-Z])";
if (specialChar) regex += "(?=.*[#$!%*?&])";
if (number) regex += "(?=.*[0-9])";
regex = "^" + regex + "[A-Za-z0-9#$!%*?&]{4,32}$";
var re = new RegExp(regex);
if (re.test(input)) {
console.log(input + " => valid");
}

Related

if the command used does not contain a valid hex code

if (command === "hex")
{ let hex = args[0]
if(!hex) return message.reply("Please specify a hex code!")
function hexToRgb(hex) {
if (hex.charAt(0) === '#') hex = hex.substring(1)
if(!hexToRgb(hex)) return message.reply("Not a valid hex.")
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
let embed = new Discord.MessageEmbed()
.setTitle("Hex Code")
.setColor(hex)
.addFields(
{
name: `RGB`,
value: hexToRgb(hex) + ``
}
)
message.channel.send({embeds: [embed]})
}
Here is my above code for the hex command. I would like the bot to send a message that it's unable to convert hex to color if the user is using an invalid hex code (e.g. #GGGGGG) or a non-hex code (e.g. "Hello"). How could I achieve that?
You can use regex. This simple function will return whether or not it is a valid hex code
String.prototype.isHex = function() {
return ( this.match(/#?[a-f0-9]+/i)?.[0] || false )
}
And run it like this
'#ffffff'.isHex() //'#ffffff'
'Hello'.isHex() //false
'#gggggg'.isHex() //false
You can use a RegExp (#[A-Za-z0-9_]{6}) to validate the string as a hexadecimal value preceded by a #
function isHex(str) {
return !!str.match(/#[A-Za-z0-9_]{6}/).length;
}
if (!isHex('some value')) return message.reply("Not a valid hex.")

How to replace Pipelet for ExportCustomerGroups in SFCC? (For removing Deprecated API usage)

function abc(){
var Site = require('dw/system/Site');
var utils= require('app_nars/cartridge/scripts/util/utils.js');
var mySite : String = (Site.getCurrent().getID() == "a") ? "" : "-" + Site.getCurrent().getID();
var customerGroupName : String ;
if (mySite == "A") {
customerGroupName = "A";
} else {
customerGroupName = "B";
}
var grpNam= utils.getGroup(customerGroupName);
var grpFileName = 'test';
/* No script api available for pipelet ExportCustomerGroups*/
var Pipelet = require('dw/system/Pipelet');
var PipeletExecutionResponse = new dw.system.Pipelet('ExportCustomerGroups').execute({
CustomerGroups: grpNam.iterator(),
ExportFile : grpFileName,
OverwriteExportFile:true
});
app.getView().render('path/templateName');
}
How can we replace the Pipelet ExportCustomerGroups here , i could see in documentation we can use job steps and there is no script replacement
You have to create with your own code, construct the xml needed while parsing the customers.[enter image description here][1]
Or you can use this step when configuring job if no custom code needed there:
[1]: https://i.stack.imgur.com/s1VQa.png

2 object of same type returns true when != checked

I am using model.GetType().GetProperties() with foreach to compare properties of 2 object of same class.
like this
foreach (var item in kayit.GetType().GetProperties())
{
var g = item.GetValue(plu);
var b = item.GetValue(kayit);
if (g is string && b is string&& g!=b)
{
a += item.Name + "*";
}
else if (g is DateTime&& b is DateTime&& g!=b)
{
a += item.Name + "*";
}
}
But the problem is even if they have the same value g!=b returns a true all the time. I have used a break point to prove this and they are literally same thing. Actually I am taking the value putting it in textbox then creating another class after button click and comaring to see the changed properties. So even if I don't change anything it doesn't read the mas equals. Can someone help me about this please?
more info:
I get the plu from database and populate my control with it:
txtorder.Text = plu.OrderNo;
dtporder.Value = nulldate(plu.OrderDate);
dtp1fit.Value = nulldate(plu.FirstFitDate);
dtp1yorum.Value = nulldate(plu.FirstCritDate);
dtp2fit.Value = nulldate(plu.SecondFitDate);
dtp2yorum.Value = nulldate(plu.SecondCritDate);
dtpsizeset.Value = nulldate(plu.SizeSetDate);
dtpsizesetok.Value = nulldate(plu.SizeSetOkDate);
dtpkumasplan.Value = nulldate(plu.FabricOrderByPlan);
txtTedarikci.Text = plu.Fabric_Supplier;
dtpkumasFP.Value = nulldate(plu.FabricOrderByFD);
dtpfabarrive.Value = nulldate(plu.FabricArrive);
dtpbulk.Value = nulldate(plu.BulkFabricDate);
dtpbulkok.Value = nulldate(plu.BulkConfirmDate);
dtpaccessory.Value = nulldate(plu.AccessoriesDate);
dtpaccessoryarrive.Value = nulldate(plu.AccessoriesArriveDate);
dtpcutok.Value = nulldate(plu.ProductionStartConfirmation);
dtpcutstart.Value = nulldate(plu.ProductionStart);
dtpshipmentdate.Value = nulldate(plu.ShipmentDate);
dtpshipmentsample.Value = nulldate(plu.ShipmentSampleDate);
dtpshippedon.Value = nulldate(plu.Shippedon);
nulldate is just a method where I change null values to my default value.
And this is what I do after button click:
var kayit = new uretim();
kayit.OrderNo = txtorder.Text.ToUpper();
kayit.OrderDate = vdat(dtporder.Value);
kayit.FirstFitDate = vdat(dtp1fit.Value);
kayit.FirstCritDate = vdat(dtp1yorum.Value);
kayit.SecondFitDate = vdat(dtp2fit.Value);
kayit.SecondCritDate = vdat(dtp2yorum.Value);
kayit.SizeSetDate = vdat(dtpsizeset.Value);
kayit.SizeSetOkDate = vdat(dtpsizesetok.Value);
kayit.FabricOrderByPlan = vdat(dtpkumasplan.Value);
kayit.Fabric_Supplier = txtTedarikci.Text;
kayit.FabricOrderByFD = vdat(dtpkumasFP.Value);
kayit.FabricArrive = vdat(dtpfabarrive.Value);
kayit.BulkFabricDate = vdat(dtpbulk.Value);
kayit.BulkConfirmDate = vdat(dtpbulkok.Value);
kayit.AccessoriesDate = vdat(dtpaccessory.Value);
kayit.AccessoriesArriveDate = vdat(dtpaccessoryarrive.Value);
kayit.ProductionStartConfirmation = vdat(dtpcutok.Value);
kayit.ProductionStart = vdat(dtpcutstart.Value);
kayit.ShipmentDate = vdat(dtpshipmentdate.Value);
kayit.ShipmentSampleDate = vdat(dtpshipmentsample.Value);
kayit.Shippedon = vdat(dtpshippedon.Value);
kayit.Status = true;
kayit.WrittenDate = DateTime.Now;
kayit.GuidKey = plu.GuidKey != null ? plu.GuidKey : Guid.NewGuid().ToString("N");
I have proven by breakpoint that values are actually same. But the != check retruns a true.
When you are doing
g != b
compiler doesn't know that these objects are strings to compare so it compares their references. You can do:
g.Equals(b) //be carefull if one of them is null
or
g.ToString() != b.ToString()
EDIT
You can compare them after you check the type:
if (g is string && b is string)
{
if( g.ToString() != b.ToString() ){
}
}

Get repeated path comparing 2 paths using c#

I have 2 file-paths.
eg:
Path 1 C:\Users\Me\FileFolder\File1.info
Path 2 C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info
I want to create a method to extract the repeated path:
Result C:\Users\Me\FileFolder
Is there a method to do this? Or how it can be done?
It can be done using String.Split method and Enumerable.TakeWhile
var part1 = path1.Split(Path.DirectorySeparatorChar);
var part2 = path2.Split(Path.DirectorySeparatorChar);
var commonParts = part1.TakeWhile((x,idx) => idx < part2.Length && part2[idx] == x);
if (commonParts.Any())
{
var result = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
}
Fiddle
I assume you want to find all common folders, so the path that is shared from both, try this:
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string root1 = Path.GetPathRoot(path1);
string root2 = Path.GetPathRoot(path2);
if (root1.Equals(root2, StringComparison.InvariantCultureIgnoreCase))
{
string[] folders1 = path1.Split(Path.DirectorySeparatorChar);
string[] folders2 = path2.Split(Path.DirectorySeparatorChar);
var commonFolders = folders1.TakeWhile((dir, index) =>
folders2.Length > index &&
dir.Equals(folders2[index], StringComparison.InvariantCultureIgnoreCase));
string commonFolderPath = string.Format("{0}{1}"
, root1
, Path.Combine(commonFolders.Skip(1).ToArray())); // Skip(1) skips root
Console.Write(commonFolderPath);
}
Result: C:\Users\Me\FileFolder
Alternative way is to use Zip with TakeWhile (suggested by Selman22).
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string[] part1 = path1.Split(Path.DirectorySeparatorChar);
string[] part2 = path2.Split(Path.DirectorySeparatorChar);
string[] commonParts = part1.Zip(part2, (p1, p2) => p1 == p2 ? p1 : null)
.TakeWhile(s => s != null)
.ToArray();
string commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);
Slightly changed example of Selman22.
string path1 = #"C:\Users\Me\FileFolder\File1.info";
string path2 = #"C:\Users\Me\FileFolder\DirectoryContent\Content1\File.info";
string[] part1 = path1.Split(Path.DirectorySeparatorChar);
string[] part2 = path2.Split(Path.DirectorySeparatorChar);
string[] commonParts = Enumerable.Range(0, Math.Min(part1.Length, part2.Length))
.TakeWhile(i => part1[i] == part2[i])
.Select(i => part1[i])
.ToArray();
string commonPath = string.Join(Path.DirectorySeparatorChar.ToString(), commonParts);

AS3/Flash: XML to array

How may I populate an array formated like this?:
var names:Array = [{label:"JAMES"}, {label:"JANE"}, {label:"JAMEL"}...];
From a XML like this one?:
<a>
<ap>
<name>JAMES</name>
<age>36</age>
</ap>
</a>
This is for AutoComplete components.
UPDATE, to start with something more suitable to my skills. THIS:
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>
TO THIS:
var list:Array = [{label:"ALPHA"}, {label:"ALLAN"}, {label:"ANTARES"}...];
const xml:XML =
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>;
const list:Array = new Array();
//xml..label.(trace(text()));
xml..label.(list.push({label:text()}));
// now we have an array:
// [{label:"ALPHA"}, {label:"ALLAN"}, {label:"ANTARES"}, {label:"..."}]
I recommend to read the AVM2 specification and to pay special attention to namespaces. Seriously. It's interesting and it's fun!
Hmmm... Alternative boring way:
const list:Array = new Array();
const xml:XML =
<list>
<label>ALPHA</label>
<label>ALLAN</label>
<label>ANTARES</label>
<label>...</label>
</list>;
const labels:XMLList = xml..label;
for each(var node:XML in labels)
{
trace(node);
var arrayItem:Object = new Object();
arrayItem.label = node.text(); // or node.toString() or .toJSON() or .to...
arrayItem.name = node.name();
// added only for debug-trace:
arrayItem.toString = function():String
{
var result:String = '{', delimiter:String = '';
for(var key:String in this)
if(key !== 'toString')
result += delimiter + key + ':"' + this[key] + '"',
delimiter ||= ', ';
return result + '}';
}
// add item to list:
list.push(arrayItem);
}
trace(list);

Resources