Test for empty string in Mongoose regular expression - regex

Everything I've found indicates that an empty string can be matched in a regular expression by /^$/. However, that expression is not working in my Mongoose Validator for zipcode.
I want to set zipcode if one of two states is true - either it is empty or it is a valid, five digit number.
ZIP_REGEX: /^$|^[0-9]{5}$/
zip: {
type: Number,
validate: [ ZIP_REGEX, 'ValidationError']
},
This validator fails each time I attempt to store an empty string. The result is I can set valid zipcode, but never unset them. Is Mongoose also trying to verify that the empty string is a Number? Is the regular expression wrong?

Use a custom validation function for anything a bit unusual like this. Assuming you want to support both numbers and strings as input:
function validator(v) {
return (!v && v !== 0) || /^[0-9]{5}$/.test(v.toString());
};
zip: {
type: Number,
validate: [validator, 'ValidationError']
},

Related

calculate range of values entered by user Custom function Google Appscript

I want to use arrayformula for my custom function if possible because I want to input a range of values
I also get this error: TypeError: Cannot read property "0" from null.
Also, this: Service invoked too many times in a short time: exec qps. Try Utilities.sleep(1000) between calls
var regExp = new RegExp("Item: ([^:]+)(?=\n)");
var matches=new regExp(input);
return matches[0];
}
Really appreciated some help
Edit:
Based on the second picture, I also try using this regex formula to find word start with "Billing address"
But for the first picture, I used regex formula to find word start with "Item"
The error appears the same for both custom function.
If you want to use a custom function which finds all the strings that start with Item or item and extracts the contents from after the finding, you can use the code provided below. The regular expression is checked by using the match() function and returns the desired result; otherwise, it will return null.
function ITEM(input) {
var regEx = /(?:I|i)tem\s*(.*)$/;
var matches = input.match(regEx);
if (matches && matches.length > 1) {
return matches[1];
} else {
return null;
}
}
If you want to use the RegExp like you did in the code you have shared, you should use \\ instead of \.
For checking and verifying the regular expressions you can use this site.
The Service invoked too many times in a short time: exec qps. Try Utilities.sleep(1000) between calls. error message you are getting is due to the fact that you are trying to call the custom function on too many cells - for example dragging the custom function on too many cells at once. You can check more about this error message here.

How to validate password using express-validator npm

I am writing rest API using node , express web module. For validation I am using express-validator npm. I want to apply some validation rules on password field.
How can I achieve it using express-validator?
What validation rules I want to apply for password as:
min 8 char long.
At least one uppercase.
At least one lower case.
At least one special character.
I read in this link that there is a function available called regex() . So I tried it but not working at all.
My approach:
req.check("password", "Password should be combination of one uppercase , one lower case, one special char, one digit and min 8 , max 20 char long").regex("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/", "i");
Error
In express-js they have listed all the methods but did not find method / trick which solve my problem.
The link you're referring to is almost 3 years old. Since then, the API of validator changed.
To check against a regular expression, use .matches():
req.check("password", "...").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i");
I believe the accepted answer is outdated. RegExp and express-validator are not the best ways to validate passwords in 2017, as the obscurity of regular expressions makes the app unmaintainable and prone to bugs.
password-validator makes it easy to define password rules and maintain them. Here's a sample:
var passwordValidator = require('password-validator');
var schema = new passwordValidator();
schema
.is().min(8)
.is().max(100)
.has().uppercase()
.has().lowercase();
console.log(schema.validate(req.body.password)); // prints a boolean
PS: I'm the author of the password-validator.
Theres a new solution for this. From the documentation:
Check if a password is strong or not. Allows for custom requirements or scoring rules. If returnScore is true, then the function returns an integer score for the password rather than a boolean.
Default options:
body('password').isStrongPassword({
minLength: 8,
minLowercase: 1,
minUppercase: 1,
minNumbers: 1,
minSymbols: 1,
returnScore: false,
pointsPerUnique: 1,
pointsPerRepeat: 0.5,
pointsForContainingLower: 10,
pointsForContainingUpper: 10,
pointsForContainingNumber: 10,
pointsForContainingSymbol: 10,
})
Using the built in validators of express-validator I was able to use built in validators without a regex to check the password.
const validateStrongPassword = body("password")
.isString()
.isLength({ min: 8 })
.not()
.isLowercase()
.not()
.isUppercase()
.not()
.isNumeric()
.not()
.isAlpha();
This verifies that there is at least one non letter character, one lowercase letter, one uppercase letter, a minimum length and that there are letters in the password.
Chosen answer is incomplete as it's missing validation for special characters. Correct answer should be:
req.checkBody("password", "Password must include one lowercase character, one uppercase character, a number, and a special character.").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, "i");
Only real difference is that I added the (?=.*[^a-zA-Z0-9]) expression which ensures a user is using a character that's not a number or letter.
check(
"password1",
"Please enter a password at least 8 character and contain At least one uppercase.At least one lower case.At least one special character. ",
)
.isLength({ min: 8 })
.matches(
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d#$.!%*#?&]/,
)
In case you are using an array for validation and therefore the req object is not available, you can also do the following:
body('field_name').matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i").withMessage('Password should be combination of one uppercase , one lower case, one special char, one digit and min 8 , max 20 char long'),
matches method work but I think it's not a stable for this use case, I think you should use the custom() method my code's :
this method work with tow parameters first is the value of your fieldset that in check method for example check('name field or password field') and the second value is an object that includes req object and you can use them and return a true or false if your returned value is true it's ok but if you return false its problem and validation is failed.
I write code in different shapes.
router.post('/adduser', [check('name').isLength({
min: 2,
max: 25
}).withMessage('min character 2 nad max character 25').custom((value, {req}) => {
return !req.body.name.match(/[^a-zA-Z]/g)
}).withMessage('please write a correct name'),
check('family').isLength({
min: 2,
max: 25
}).withMessage('min character 2 nad max character 25').custom((value, {req}) => {
return !req.body.name.match(/[^a-zA-Z]/g)
}).withMessage('please write a correct family'),
check('number').custom((value, {req}) => {
return !req.body.name.match(/[^a-zA-Z]/g)
})], (req, res, next) => {
console.log(validationResult(req).errors)
})

how to match a input value with the regular expression in dynamics crm 2011?

At the contact form I have a field name as Extension (new_ext). and at the onChnage event I want to do check weather the user has enter the number or anything else. I have the following piece of code.
function formatPhone(phonenum)
{
var ext =phonenum.getEventSource().getValue();
var reg = /^[0-9]$/;
if(ext.match(reg))
{
alert("Valid");
}
else
{
alert("invalid");
}
}
It returns me always invalid even if I enter a letter or a number or both.
I want to seek your kind suggestions and help regarding this.
Try this one "^\d+$", just check for null values before if you need to.
Already asked here Regex allow a string to only contain numbers 0 - 9

Validating a Salesforce Id

Is there a way to validate a Salesforce ID, maybe using RegEx? They are normally 15 chars or 18 chars but do they follow a pattern that we can use to check that it's a valid id.
There are two levels of validating salesforce id:
check format using regular expression [a-zA-Z0-9]{15}|[a-zA-Z0-9]{18}
for 18-characted ids you can check the the 3-character checksum:
Code examples provided in comments:
C#
Go
Javascript
Ruby
Something like this should work:
[a-zA-Z0-9]{15,18}
It was suggested that this may be more correct because it prevents Ids with lengths of 16 and 17 characters to be rejected, also we try to match against 18 char length first with 15 length as a fallback:
[a-zA-Z0-9]{18}|[a-zA-Z0-9]{15}
Just use instanceOf to check if the string is an instance of Id.
String s = '1234';
if (s instanceOf Id) System.debug('valid id');
else System.debug('invalid id');
The easiest way I've come across, is to create a new ID variable and assign a String to it.
ID MyTestID = null;
try {
MyTestID = MyTestString; }
catch(Exception ex) { }
If MyTestID is null after trying to assign it, the ID was invalid.
This regex has given me the optimal results so far.
\b[a-z0-9]\w{4}0\w{12}|[a-z0-9]\w{4}0\w{9}\b
You can also check for 15 chars, and then add an extra 3 chars optional, with an expression similar to:
^[a-z0-9]{15}(?:[a-z0-9]{3})?$
on i mode, or not:
^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$
Demo
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
Javascript: /^(?=.*?\d)(?=.*?[a-z])[a-z\d]{18}$/i
These were the Salesforce Id validation requirements for me.
18 characters only
At least one digit
At least one alphabet
Case insensitive
Test cases
Should fail
1
a
1234
abgcde
1234aDcde
12345678901234567*
123456789012345678
abcDefghijabcdefgh
Should pass
1234567890abcDeFgh
1234abcd1234abcd12
abcd1234abcd1234ab
1abcDefhijabcdefgf
abcDefghijabcdefg1
12345678901234567a
a12345678901234567
For understanding the regex, please refer this thread
The regex provided by Daniel Sokolowski works perfectly to verify if the id is in the correct format.
If you want to verify if an id corresponds to an actual record in the database, you'll need to first find the object type from the first three characters (commonly known as prefix) and then query the object type:
boolean isValidAndExists(String key) {
Map<String, Schema.SObjectType> objTypes = Schema.getGlobalDescribe();
for (Schema.SObjectType objType : objTypes.values()) {
Schema.DescribeSObjectResult objDesc = objType.getDescribe();
if (objDesc.getKeyPrefix() == key.substring(0,3)) {
String objName = objDesc.getName();
String query = 'SELECT Id FROM ' + objName + ' WHERE Id = \'' + key + '\'';
SObject[] objs = Database.query(query);
return !objs.isEmpty();
}
}
return false;
}
Be aware that Schema.getGlobalDescribe can be an expensive operation and degrade the performance of your application if you use that often.
If you need to check that often, I recommend creating a Custom Setting or Custom Metadata to store the relation between prefixes and object types.
Assuming you want to validate Ids in Apex, there are a few approaches discussed in the other answers. Here is an alternative, with notes on the various approaches.
The try-catch method (credit to #matt_k) certainly works, but some folks worry about overhead, especially if testing many Ids.
I used instanceof Id for a long time (credit to #melani_s), until I discovered that it sometimes gives the wrong answer (e.g., '481D0B74-41CF-47E9').
Multiple answers suggest regexen. As the accepted answer correctly points out (credit to #zacheusz), 18 character Ids are only valid if their checksums are correct, which means the regex solutions can be wrong. That answer also helpfully provides code in several languages to test Id checksums. But not in Apex.
I was going to implement the checksum code in Apex, but then I realized the Salesforce had already done the work, so instead I just convert 18 digit Ids to 15 digit Ids (via .to15() which uses the checksum to fix capitalization, as opposed to truncating the string) and then back to 18 digits to let SF do the checksum calc, then I compare the original checksum and the new one. This is my method:
static Pattern ID_REGEX = Pattern.compile('[a-zA-Z0-9]{15}(?:[A-Z0-5]{3})?');
/**
* #description Determines if a string is a valid SalesforceId. Confirms checksum of 18 digit Ids.
* Works for cases where `x instanceof id` returns the wrong answer, like '481D0B74-41CF-47E9'.
* Does NOT check for the existence of a record with the given Id.
* #param s a string to validate
*
* #return true if the string `s` is a valid Salesforce Id.
*/
public static Boolean isValidId(String s) {
Matcher m = ID_REGEX.matcher(s);
if (m.matches() == false) return false; // if it doesn't match the regex it cannot be valid
if (s.length() == 15) return true; // if 15 char string matches the regex, assume it must be valid
String check = (Id)((Id)s).to15(); // Convert to 15 char Id, then to Id and back to string, giving correct 18-char Id
return s.right(3) == check.right(3); // if 18 char string matches the regex, valid if checksum correct
}
Additionally checking getSObjectType() != null would be perfect if we are dealing with Salesforce records
public static boolean isRecordId(string recordId){
try{
return string.isNotBlank(recordId) && ((Id)recordId.trim()).getSObjectType() != null;
}catch(Exception ex){
return false;
}
}

Searching for a pattern in Ext JS

I have a grid with certain records and a textfield above it. The textfield is connected with the grid such that each time there is a keyup event it goes to a filter function in order to only show those records that contain the characters that the user typed in. The problem is that right now it only matches from the starting character of the record string name, however id like it to be able to filter all those records that contain the typed in characters anywhere in the record string name.
Screenshots:-
http://imgur.com/a/qvIHO
The first image shows the records, second shows the filtered results when i type in 'c', the third shows that when i press in 'p' it doesn't return any result however i want it to return "GPL Products" and "Reporting Period" since they both contain 'p' in them.
Here's the code:-
onDimensionFilterTextBoxKeyUp: function (filterTxtBox, evntObj, eOpts) {
var dimStore = this.getDimensionStoreStore();
//get new value
var searchValue = filterTxtBox.getValue();
//var regex = /searchValue*/;
//clear previous search value
dimStore.clearFilter();
if (!Ext.isEmpty(searchValue)) {
//load filtered data
dimStore.filter('DimensionName', searchValue);
}
}
I tried creating a regexp pattern using the /searchValue*/ but using that just breaks the filter and it doesn't return even a single result.
Try this:
re = new RegExp(searchValue, ignoreCase ? 'i' : '');
store.filter(field, re);
You just need to specify a case-insensitive search.
dimStore.filter('DimensionName', searchValue, true, false);
I know that those answers above are old, but maybe can help someone.
store.filter({
anyMatch: true,
exactMatch: false,
property: valor_property,
value: valor
});