I have a personal function who take an id and a pattern for check some input.
var id, schema;
function checkField(id, schema){
var input = id.val();
var pattern = schema;
if (!input.match(pattern)){
console.log('Input = '+input);
console.log('Pattern = '+pattern);
id.removeClass().addClass("error");
$(".oke").css({display: 'none'});
}else{
console.log('Classe = ok');
id.removeClass().addClass("ok");
$(".nope").css({display: 'none'});
}
}
// Vérification téléphone
$("#tel").focusout(function(){
checkField($(this), "/0[1-7,9]\d{8}/");
});
// Vérification code postale
$("#cp").focusout(function(){
checkField($(this), "/^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$/");
});
But the if condition always return null (!input.match(pattern)).
The two console log return the number write in input, and the pattern correctly, why the if is always false ?
When you pass "/0[1-7,9]\d{8}/" to the String#match(), the single \ before d is removed as it is an unknown escape sequence and the / around the pattern are treated as literal / symbols in the pattern. Thus, you get no matches. Also, the , in the character class is also considered a literal comma, I am sure you want to remove it from the pattern. Besides, the first pattern lacks ^ at the start and $ anchor at the end if you plan to match the entire string. Either pass "^0[1-79]\\d{8}$" or - preferred - use a regex literal /^0[1-7,9]\d{8}$/ (no double quotes around the pattern).
The second pattern can be shortened as /^(0[1-9]|[1-8]\d|9[0-8]|2[AB])\d{3}$/ - again, note the absence of the double quotes around the regex literal notation.
Also, it is advisable to replace if (!input.match(pattern)) with if (!pattern.test(input)) as regex.test(str) returns true or false while str.match(regex) will either return null or an array of match data.
So, what you can use is
if (!pattern.test(input)){
...
$("#tel").focusout(function(){
checkField($(this), /^0[1-79]\d{8}$/);
});
$("#cp").focusout(function(){
checkField($(this), /^(0[1-9]|[1-8]\d|9[0-8]|2[AB])\d{3}$/);
})
JavaScript regex patterns are not strings, you should remove the double quotes.
$("#tel").focusout(function(){
checkField($(this), /0[1-7,9]\d{8}/);
});
$("#cp").focusout(function(){
checkField($(this), /^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$/);
})
Related
I have a question related to formatting strings.
User should parse a string in the Format XX:XX.
if the string parsed by user is in the format XX:XX i need to return true,
else false:
app.post('/test', (req, res) => {
if (req.body.time is in the format of XX:XX) {
return true
} else {
return false
}
});
You can use the RegExp.test function for this kind of thing.
Here is an example:
var condition = /^[a-zA-Z]{2}:[a-zA-Z]{2}$/.test("XX:XX");
console.log("Condition: ", condition);
The regex that I've used in this case check if the string is composed from two upper or lower case letters fallowed by a colon and other two such letters.
Based on your edits it seems that you're trying to check if a string represents an hour and minute value, if that is the case, a regex like this will be more appropriate /^\d{2}:\d{2}$/. This regex checks if the string is composed of 2 numbers fallowed by a colon and another 2 numbers.
The tool you're looking for is called Regular Expressions.
It is globally supported in almost every development platform, which makes it extremely convenient to use.
I would recommend this website for working out your regular expressions.
/^[a-zA-Z]{2}:[a-zA-Z]{2}&/g is an example of a Regular Expression that will take any pattern of:
[a-zA-Z]{2} - two characters from the sets a-z and A-Z.
Followed by :
Followed by the same first argument. Essentially, validating the pattern XX:XX. Of course, you can manipulate it as to what you want to allow for X.
^ marks the beginning of a string and $ marks the end of it, so ASD:AS would not work even though it contains the described pattern.
try using regex
var str = "12:aa";
var patt = new RegExp("^([a-zA-Z]|[0-9]){2}:([a-zA-Z]|[0-9]){2}$");
var res = patt.test(str);
if(res){ //if true
//do something
}
else{}
I am holding in a field the validation format that I would need.
I need to convert different ## into a regex validation.
Is there a simple replace that can do this for me.
for example, i need to validate the account number.
sometimes it might need to be ###-###, or I'll get ####### or ##-####.
depending what is in the id="validationrule" field
I'm looking for
regex = $('#validationrule').replace("#", "[0/9]");
It also has to take into consideration that sometimes there is a dash in there.
Your question seems to be about creating regexes from a string variable (which you get from an input field that specifies the validation format).
"###-###" might turn into /^\d{3}\-\d{3}$/
"#######" might turn into /^\d{7}$/
If your validation format is built from the 2 characters # and -, this would work:
function createValidationRegEx(format){
format = format
.replace(/[^#\-]/g, '') //remove other chars
.replace(/#/g, '\\d') //convert # to \d
.replace(/\-/g, '\\-'); //convert - to \-
return new RegExp('^' + format + '$', 'g');
}
//create regexes
var format1 = createValidationRegEx('###-###');
var format2 = createValidationRegEx('#######');
//test regexes
console.log(format1.test('123-456')); // true
console.log(format2.test('123-456')); // false
console.log(format1.test('1234567')); // false
console.log(format2.test('1234567')); // true
Please note that you need to pay attention to which characters needs to be escaped when creating regexes from strings. This answer provides more details about how to solve this more generally, if you want to build more complex solutions.
If you are trying to replace the .value of an <input> element you can use .val(function), return replacement string from .replace() inside of function, chain .val() to assign result to regex. Use RegExp constructor with g flag to replace all matches of the RegExp supplied to .replace() to match characters against at string.
var regex = $("#validationrule").val(function(_, val) {
return val.replace("#", "[0/9]");
}).val();
console.log(regex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="validationrule" value="#">
I have string patterns like name1|value1, name1|value1,name2|value2, name1| and name1|value1,. I have to have Regular expression to find the given pattern is true or false
Input and output would be
"name1|value1" -> true
"name1|value1,name2|value2" -> true
"name1|" -> false
"name1|value1," -> false
"name1|value1,name2" -> false
"name1|value1,name2|" -> false
Pretty simple: ^\w+\|\w+(,\w+\|\w+)*$
The first portion, ^\w+\|\w+ looks to make sure the string starts with at least 1 completed name|value pair.
Then the second portion, (,\w+\|\w+)* says that same pattern may repeat infinitely as long as there is a comma between the first pair and all subsequent pairs. (Although, the asterisk quantifies that the second portion of the pattern may not occur at all.)
Finally the $ says that the string must end matching this pattern. (I.e., this pattern cannot only match part of the string. It must match the entire string because of the ^ and $.)
To format this pattern for javascript, simply throw a forward slashes on both ends, so: /^\w+\|\w+(,\w+\|\w+)*$/ The pattern should not require any flags.
It is worth noting, if you need to match more complex names/values that are outside the character range of \w, then you should replace all \ws with [Some Character Set(s)].
If your have multiple pairs to check, you can apply your regex on splitted string elements with an every function:
isValidPairs = function(str) {
return str.split(',').every(function(elt) {
return /^\w+\|\w+$/.test(elt);
});
}
pairsArr = ["nam1|val1", "nam1|val1,name2|val2", "nam1|", "nam1|val1,", "nam1|val1,name", "nam1|val1,name|"];
pairsArr.forEach(function(str) {
console.log('%s: %s:', str, isValidPairs(str));
});
Ok, so I have multiple inputs that receive UUID codes. So Im using the .each function from jQuery to go one by one and validate the input to be a UUID code. So this is the code that I have until now:
function validateAll(){
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/ig;
$('input.offer').each(function(x){
if($(this).val() !== ""){
console.log(x+" - "+$(this).val()+" - "+regex.test($(this).val()));
}
});
return true;
}
Now when I run this with two inputs being: 00000000-0000-0000-0000-000000000000 this is what I get in the console:
0 - 00000000-0000-0000-0000-000000000000 - true
1 - 00000000-0000-0000-0000-000000000000 - false
Why the regex.test() is validating the first one but not second one? Thanks.
You need to bring the regex instantiation within the loop - it cannot be retested against another string.
function validateAll(){
$('input.offer').each(function(x) {
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/ig;
if($(this).val() !== ""){
console.log(x + " - " + $(this).val() + " - " + regex.test($(this).val()));
}
});
return true;
}
Example fiddle
The reason the second iteration fails:
when [the regex] is a global regular expression. It will attempt to match from the index of the last match in any previous string.
Article: Be careful when reusing regex objects
Remove the g modifier from the regexp. When you reuse a regexp with this modifier, it starts the new test from the index of the last match, rather than the beginning of the new string. This modifier serves no purpose when using Regex::test, since it only tells you if the regexp matches anywhere -- multiple matches are redundant. So it should be:
var regex = /^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/i;
Also, I wonder why you put both a-z and A-Z in your character classes when you also use the i modifier to make it case-insensitive.
FIDDLE
I am trying to use regular expession in javascript but it is not working. My custom control contains property called RegEx which is provided by user and I need to validate the input value against this regex. As properties in JS will be in double quotes("") the regualr expression fails(case -1). Case 2 succeeds thought both the cases regualr expression is same, the only difference is case- 1 it goes as double quotes. can somebody tell me why it is not working.
RegexExp="/^\d{5}$/"- at my aspx page
var value = "11111";
if(value.toString().search($(element).attr('RegexExp')) != -1)
{
return true;
}
else
{
return false;
}
var reg = /^\d{5}$/;
if(value.toString().search(reg) != -1)
{
return true;
}
else
{
return false;
}
Do this instead:
var reg = new RegExp($(element).attr('RegexExp'));
Update: you also need to strip the / characters, as these shouldn't be given to the RegExp constructor:
var regexExp = $(element).attr('RegexExp');
var reg = new RegExp(regexExp.substring(1, regexExp.length - 1));
I assume that the code that you posted is part of the function from the return statements, but if it is not, your first problem is that return is not allowed to be used out side of functions.
In any case, try the following. You can create a RegExp from a string by using its formal constructor
value.search(new RegExp($(element).attr('RegexExp')));
Also, you do not need to use toString() on value since it is already a string and your code is unnecessarily verbose. The following is equivalent to your first if else statement
return value.search(new RegExp($(element).attr('RegexExp'))) != -1;
Edit:
If you want to be able to pass in an expression as "/[expression]/" or "/[expression]/gi", you can do the following:
var toRegExp = function(regexString) {
var expression = regexString.substr(1), // remove first '/'
closingSlash = expression.lastIndexOf("/"); // find last '/'
return new RegExp(
// Expression: remove everything after last '/'
expression.substr(0, closingSlash),
// Flags: get everything after the last '/'
expression.substr(closingSlash+1)
);
}
....
value.search( toRegExp($(element).attr('RegexExp')) );
First, don't use a custom attribute to hold a regular expression. Second, "RegexExp" is redundant — that's like saying "regular expression expression". Third, to convert from a String to a RegExp, you have to wrap the string with new RegExp(); JavaScript is not weakly typed. That said, assuming that the regular expression isn't being set server-side, I'd recommend using jQuery's data API. It has the added advantage that it can store regular expression objects directly.
To set:
jQuery.data($(element).get(0), "regexp", /^\d{5}$/);
To get:
jQuery.data($(element).get(0), "regexp");
But ultimately, what you really want is the jQuery Validation plugin. It does everything you need and then some. Incidentally, it uses the data API internally to work its magic.
Documentation
The /.../ syntax is used to declare a regular expression object in Javascript, so you shouldn't use that to specify a regular expression pattern, it should be just regexp="^\d{5}$" as the attribute.
The search method takes a regular expression object as parameter, so you have to create a regular expression object from the string that you get from the attribute:
var reg = new RegExp($(element).attr('regexp'));
if (value.toString().search(reg) != -1) {
(You see the similarity with your second case?)
Or as a single expression:
if (value.toString().search(new RegExp($(element).attr('regexp'))) != -1) {