Javascript regexp using val().match() method - javascript

I'm trying to validate a field named phone_number with this rules:
the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874
or can be 7 numbers 1234567
here i have my code:
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
missing = true;
Why doesnt work :( when i put that into an online regexp checker shows good.

You should be using test instead of match and here's the proper code:
.test(/^(3\d{9}|\d{7})$/)
Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).

Don't get confused by pipe. Must end each expression
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
missing = true;
http://jsfiddle.net/alfabravoteam/e6jKs/

I had similar problem and my solution was to write it like:
if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
missing = true;
}

Try this, it's a little more strict.
.match(/^(3\d{9}|\d{7})$/)

Related

Use only one of the characters in regular expression javascript

I guess that should be smth very easy, but I'm stuck with that for at least 2 hours and I think it's better to ask the question here.
So, I've got a reg expression /&t=(\d*)$/g and it works fine while it is not ?t instead of &t in url. I've tried different combinations like /\?|&t=(\d*)$/g ; /\?t=(\d*)$|/&t=(\d*)$/g ; /(&|\?)t=(\d*)$/g and various others. But haven't got the expected result which is /\?t=(\d*)$/g or /&t=(\d*)$/g url part (whatever is placed to input).
Thx for response. I think need to put some details here. I'm actually working on this peace of code
var formValue = $.trim($("#v").val());
var formValueTime = /&t=(\d*)$/g.exec(formValue);
if (formValueTime && formValueTime.length > 1) {
formValueTime = parseInt(formValueTime[1], 10);
formValue = formValue.replace(/&t=\d*$/g, "");
}
and I want to get the t value whether reference passed with &t or ?t in references like youtu.be/hTWKbfoikeg?t=82 or similar one youtu.be/hTWKbfoikeg&t=82
To replace, you may use
var formValue = "some?some=more&t=1234"; // $.trim($("#v").val());
var formValueTime;
formValue = formValue.replace(/[&?]t=(\d*)$/g, function($0,$1) {
formValueTime = parseInt($1,10);
return '';
});
console.log(formValueTime, formValue);
To grab the value, you may use
/[?&]t=(\d*)$/g.exec(formValue);
Pattern details
[?&] - a character class matching ? or &
t= - t= substring
(\d*) - Group 1 matching zero or more digits
$ - end of string
/\?t=(\d*)|\&t=(\d*)$/g
you inverted the escape character for the second RegEx.
http://regexr.com/3gcnu
I want to thank you all guys for trying to help. Special thanks to #Wiktor Stribiżew who gave the closest answer.
Now the piece of code I needed looks exactly like this:
/[?&]t=(\d*)$/g.exec(formValue);
So that's the [?&] part that solved the problem.
I use array later, so /\?t=(\d*)|\&t=(\d*)$/g doesn't help because I get an array like [t&=50,,50] when reference is & type and the correct answer [t?=50,50] when reference is ? type just because of the order of statements in RegExp.
Now, if you're looking for a piece of RegExp that picks either character in one place while the rest of RegExp remains the same you may use smth like this [?&] for the example where wanted characters are ? and &.

Combine whitelist and blacklist in javascript regex expression

I am having problems constructing a regex that will allow the full range of UTF-8 characters with the exception of 2 characters: _ and ?
So the whitelist is: ^[\u0000-\uFFFF] and the blacklist is: ^[^_%]
I need to combine these into one expression.
I have tried the following code, but does not work the way I had hoped:
var input = "this%";
var patrn = /[^\u0000-\uFFFF&&[^_%]]/g;
if (input.match(patrn) == "" || input.match(patrn) == null) {
return true;
} else {
return false;
}
input: this%
actual output: true
desired output: false
If I understand correctly, one of these should be enough:
/^[^_%]*$/.test(str);
!/[_%]/.test(str);
Use negative lookahead:
(?!_blacklist_)_whitelist_
In this case:
^(?:(?![_%])[\u0000-\uFFFF])*$
Underscore is \u005F and percent is \u0025. You can simply alter the range to exclude these two characters:
^[\u0000-\u0024\u0026-\u005E\u0060-\uFFFF]
This will be just as fast as the original regex.
But I don't think that you are going to get the result you really want this way. JS can only go up to \uFFFF, anything past that will be two characters technically.
According to here, the following code returns false:
/^.$/.test('💩')
You need to have a different way to see if you have characters outside that range. This answer gives the following code:
String.prototype.getCodePointLength= function() {
return this.length-this.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g).length+1;
};
Simply put, if the number returned by that is not the same as the number returned by .length() you have a surrogate pair (and thus you should return false).
If your input passes that test, you can run it up against another regex to avoid all the characters between \u0000-\uFFFF that you want to avoid.

Javascript RegExp test

I am trying to verify a pattern of 5 characters - 5 characters - 5 characters with Javascript and I want it to fail if there are more or less than 5 characters between dashes. My test is as follows:
var patterns = new RegExp("[2-46-9A-DF-HJKMP-RTVW-YX]{5}-[2-46-9A-DF-HJKMP-RTVW-YX]{5}-[2-46-9A-DF-HJKMP-RTVW-YX]{5}","gi");
if(patterns.test(fkLicense) == true) {
alert('good');
} else {
alert('bad');
}
My issue is, no matter what I set the value of fkLicense to, the test fails. Any help will be greatly appreciated.
I'm not sure what you're trying to match, but the problem is that you need to anchor your regular expression and it's alot easier to use a regular expression literal here instead ...
var patterns = /^ .... $/i
eval.in

Negated character not working as expected ? ^

I want to allow my users to enter a phone number and choose their own way of seperating the numbers (or not). So I came up with a regex:
var regex = /[^0-9 \/-\\\(\)\+]/;
In most cases it works fine, but there are some examples like #,:,; where it doesn't work as I would expect. Could someone give me some hint please ?
Here's an example of what I mean
testvar = '123#213';
var regex = /[^0-9 \/-\\\(\)\+]/;
if(regex.test(testvar) === true)
{ alert('Chars out of regex-range found'); } // won't fire!
There's a long way from / to \ if you meant it. And if not, you're missing a slash before the dash:
var regex = /[^0-9 \/\-\\\(\)\+]/;
A phone number only uses digits, I'd ignore the user format and just keep the digits
var phonenum=value.replace(/\D+/g,'');

Test Password with Regex

I want to test a passwprd which must have at least 6 characters and 1 number in it. What regex string I can use with JS to get this done?
UPDATED
I forgot to write it must have at least 6 alpha characters and 1 numeric character but it should also allow special characters or any other character. Can you please modify your answers? I greatly appreciated your responses
This does smell a little like a homework question, but oh well. You can actually accomplish this concisely using a single regular expression and the "look ahead" feature.
/(?=.{6}).*\d.*/.test("helelo1")
The first bit in the brackets says "peek ahead to see if there's 6 characters". Following this we check for any number of characters, followed by a number, followed by any number of characters.
It is even possible to accomplish your goal in a single regex without having the faculty of look ahead... It's just a little hard to look at the solution and not wince:
new RegExp("[0-9].....|" +
".[0-9]....|" +
"..[0-9]...|" +
"...[0-9]..|" +
"....[0-9].|" +
".....[0-9]").test("password1")
Try this:
password.match(/(?=.*\d).{6}/);
More info here.
As far as I know this is best done with a combination of string functions and regex:
if( myPass.match(/[a-zA-Z]/).length >= 6 && myPass.match(/\d/g).length ) {
// Good passwords are good!
}
EDIT: Updated to include the new stipulations. Special characters are allowed, but not required.
if (/.{6,}/.test(password) && /\d/.test(password)) {
// success
} else {
// fail
}
/^(?=[\w\d]{6,}$)(?=.*\d)/.test(password)
requires 6 or more characters (letters, numbers or _)
requires at least one digit
won't allow any special characters
This is a js to check password,
it checks min 7 chars, contains 1 Upper case and 1 digit and 1 special character and must not contain a space, hope it will help you.
pwLength = this.value.length;
if (pwLength > 7 && pwLength < 21) {
charLengthIcon.removeClass("fail").addClass("pass");
}
else charLengthIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[A-Z]/g)) {
capLetterIcon.removeClass("fail").addClass("pass");
}
else capLetterIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[0-9]/g)) {
numberIcon.removeClass("fail").addClass("pass");
}
else numberIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[##$%!$&~*^(){}?><.,;:"'-+=|]/g)) {
splcharIcon.removeClass("fail").addClass("pass");
}
else splcharIcon.removeClass("pass").addClass("fail");
if (this.value.match(/[\s/]/g)) {
whiteSpce.removeClass("pass").addClass("fail");
}
else whiteSpce.removeClass("fail").addClass("pass");
confirmPW();
});

Categories

Resources