Regular Expression only digits and blank spaces - javascript

I have a text input and I require that it only accepts digits (0-9) and blank spaces (" ").
The current regexp to validate this input is:
/((\d{1,})(\s{1,})?){1,}/
Which stands for: one or more groups base on a first group of one or more digits and an optional second group of one or more blank spaces
That will only let me introduce values as: 999999 (only digits) or " " (only blank spaces) or 91 08 8510 903 (mix of digits and spaces).
But actually, I also can insert aaa or other characters.

Dissection
Your regular expression doesn't accept only letters :
/((\d{1,})(\s{1,})?){1,}/.test('aaa') // false
Actually, any character is accepted if the input contains at least one digit :
/((\d{1,})(\s{1,})?){1,}/.test('a1a') // true
That being said, let's skim the fat from your pattern :
"{1,}" equals "+" -> ((\d+)(\s+)?)+
"(.+)?" equals ".*" -> ((\d+)\s*)+
useless brackets -> (\d+\s*)+
This result can be translated to : "one or more digits (\d+) followed by zero or more blank spaces (\s*), one or more times (()+), anywhere in the input". Alternatively, we could say : "at least one digit, anywhere in the input".
What you need is to replace "anywhere in the input" with "from the beginning to the end of the input". This is allowed by the following special characters : ^ (beginning of input) and $ (end of input). Let's make a bunch of tests to see how they work :
requirement regex input .test()
---------------------------------------------------------------------
must contain at least one digit /\d+/ 'a1a' true
must start with at least one digit /^\d+/ '1a' true
must start with at least one digit /^\d+/ 'a1' false
must end with at least one digit /\d+$/ '1a' false
must end with at least one digit /\d+$/ 'a1' true
only digits from the beginning to the end /^\d+$/ '1a1' false
Suggestion
Only digits potentially separated by one whitespace : /^\d+( \d+)*$/.
^ beginning of the input
\d+ a digit, one or more times
( \d+)* a whitespace + same as above, zero or more times
$ end of the input
Usage example :
var r = /^\d+( \d+)*$/;
var isValid = r.test(' 1 '); // false
var isValid = r.test('1 1'); // true
var isValid = r.test('1 1'); // false
More about regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.

try this one
$pattern = '/^[0-9 ]+$/';
if ( preg_match ($pattern, $text) )
{
echo 'allowed';
}

Try this regular expression
/(\d+\s*\d*)+$/
Visualize the results here http://regex101.com/r/dE5uR8
I have tested it online using
http://regexpal.com/
The above regular expression will not accept empty blank spaces at the start. You need atleast one digit. If you want to match the empty spaces at the start also change it to (\d*\s*\d*)+$ which will accept empty spaces also

Related

Validating userName using Regex

The only numbers in the username have to be at the end. There can be zero or more of them at the end.
Username letters can be lowercase and uppercase.
Usernames have to be at least two characters long. A two-letter username can only use alphabet letter characters.
I'm trying with this but I'm stalled. /\d+$\w+/gi
/^[a-z]{2,}\d*$/i is:
^ : the begining
[a-z] : a character (a to z), you can add as many allowed characters as you want
{2,} : at least 2 of them
\d* : 0 or more digits
$ : the end
i : ignore case sensetivity (both lowercases and uppercases are allowed)
Username having characters and digit and min 2 character long
/^[a-zA-Z]{2,}\d*$/i
Test result :
UserNam9 = pass
9username = fail
Userna99 = pass
usernameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = pass
Us = pass
U = fail
/^[A-z]{2,}[A-z0-9]{0,}$/
/^ // start of line
[A-z]{2,} //alphabet characters 2 or more
[A-z0-9]{0,} //numbers and alphabet
$/ // end of line
You've missed cases when there's a letter in the start, followed by 2 or more numbers.
U99 = fail
d345 = fail
My solution passes these tests, as well:
/^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i
Using positive lookahead I am making sure that in the second case there are at least 3 alphanumeric characters.
Simplified version of /^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i:
/^\D(\d{2,}|\D+)\d*$/i
Code explanation:
^ - start of input
\D - first character is a letter
\d{2,} - ends with two or more numbers
| - or
\D+ - has one or more letters next
\d* - and ends with zero or more numbers
$ - end of input
i - ignore case of input
This is my answer, it passed all the tests:
/^[a-z][a-z]+\d*$|^[a-z]\d{2,}$/i
First Part: 2 letters (or more) and zero or more numbers
Or
Second Part: 1 letter and 2 or more numbers

Need to build regex to validate password field [duplicate]

can any one help me in creating a regular expression for password validation.
The Condition is "Password must contain 8 characters and at least one number, one letter and one unique character such as !#$%&? "
^.*(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$
---
^.* : Start
(?=.{8,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
.*$ : End
Try this
((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{6,20})
Description of above Regular Expression:
( # Start of group
(?=.*\d) # must contains one digit from 0-9
(?=.*[a-z]) # must contains one lowercase characters
(?=.*[\W]) # must contains at least one special character
. # match anything with previous condition checking
{8,20} # length at least 8 characters and maximum of 20
) # End of group
"/W" will increase the range of characters that can be used for password and pit can be more safe.
You can achieve each of the individual requirements easily enough (e.g. minimum 8 characters: .{8,} will match 8 or more characters).
To combine them you can use "positive lookahead" to apply multiple sub-expressions to the same content. Something like (?=.*\d.*).{8,} to match one (or more) digits with lookahead, and 8 or more characters.
So:
(?=.*\d.*)(?=.*[a-zA-Z].*)(?=.*[!#\$%&\?].*).{8,}
Remembering to escape meta-characters.
Password with the following conditions:
At least 1 digit
At least 2 special characters
At least 1 alphabetic character
No blank space
'use strict';
(function() {
var foo = '3g^g$';
console.log(/^(?=.*\d)(?=(.*\W){2})(?=.*[a-zA-Z])(?!.*\s).{1,15}$/.test(foo));
/**
* (?=.*\d) should contain at least 1 digit
* (?=(.*\W){2}) should contain at least 2 special characters
* (?=.*[a-zA-Z]) should contain at least 1 alphabetic character
* (?!.*\s) should not contain any blank space
*/
})();
You can make your own regular expression for javascript validations;
(/^
(?=.*\d) //should contain at least one digit
(?=.*[a-z]) //should contain at least one lower case
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{8,} //should contain at least 8 from the mentioned characters
$/)
Example:- /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{7,}$/
var regularExpression = new RegExp("^^(?=.*[A-Z]{"+minUpperCase+",})" +
"(?=.*[a-z]{"+minLowerCase+",})(?=.*[0-9]{"+minNumerics+",})" +
"(?=.*[!##$\-_?.:{]{"+minSpecialChars+",})" +
"[a-zA-Z0-9!##$\-_?.:{]{"+minLength+","+maxLength+"}$");
if (pswd.match(regularExpression)) {
//Success
}

Possible to make regular expression with sub-query

I am trying to write a regular expression for a bit of javascript code that takes a user's input of a mobile number and in one regular expression, performs the following checks:
Starts with 07
Contains only numbers, whitespace or dashes
Contains exactly 11 numbers
Is this possible to do in just one regular expression and if so, how please?
I don't think it is possible with one regex, but it is possible by testing for two conditions:
if(/^07[\d\- ]+$/.test(str) && str.replace(/[^\d]/g, "").length === 11) {
//string matches conditions
}
Explanation of the regex:
^: Anchor that means "match start of string".
07: Match the string 07. Together with the above, it means that the string must start with 07.
[: Beginning of a character class i.e., a set of characters that we want to allow
\d: Match a digit (equivalent to 0-9).
\-:
" ": Match whitespace (markdown doesn't let me show a single space as code)
]: End of character class.
+: One or more of the previous.
$: Anchor that means "match end of string". Together with the ^, this basically means that this regex must apply to the entire string.
So here we check to see that the string matches the general format (starts with 07 and contains only digits, dashes or spaces) and we also make sure that we have 11 numbers in total inside the string. We do this by getting of anything that is not a digit and then checking to see that the length of the string is equal to 11.
Since #Vivin throws out the challenge :
/^07([-\s]*\d){9}[-\s]*$/
^07 : begin with digits 07
( : start group
[-\s]* : any number of - or whitespace
\d : exactly one digit
){9} : exactly 9 copies of this group (11 digits including 07)
[-\s]* : optional trailing spaces or -
$ : end of string
Of course a more useful way might be as follows
if ((telNo = telNo.replace (/[-\s]+/g, '')).match (/^07\d{9}$/)) {
....
}
which has the advantage (?) of leaving just the digits in telNo
Thank you all for trying, but after a good while trying different ideas, I finally found a working "single" regular expression:
07((?:\s|-)*\d(?:\s|-)*){9}
This make sure that it starts with 07, only contains digits, whitespace or dashes, and only 11 of them (9 plus the first 2) are numbers.
Sorry to have wasted your time.
Explanation:
() - include in capture
(?:) - do not include in capture
\s - whitespace
| - or
- - dash
* - zero or more
\d - digits only
{9} - exactly nine of what is captured

Regex split string of numbers at finding of Alpha Characters

OK Regex is one of the most confusing things to me. I'm trying to do this in Javascript. I have a search field that the user will enter a series of characters. Codes are either:
999MC111
or just
999MC
There is ALWAYS 2 Alpha characters. BUT there may be 1-4 characters at the front and sometimes 1-4 characters at the end.
If the code ENDS with the Alpha characters, then I run a certain ajax script. If there are Numbers + 2 letters + numbers....it runs a different ajax script.
My struggle is I know \d is for 2 digits....but it may not always be 2 digits.
So what would my regex code be to split this into an array. or something.
I think correct regex would be (/^([0-9]+)([a-zA-z]+)([0-9]+)$/
But how do i make sure its ONLY 2 alpha characters in middle?
Thanks
You could use the regex /\d$/ to determine if it ends with a decimal.
\d matches a decimal character, and $ matches the end of the string. The / characters enclose the expression.
Try running this in your javascript console, line by line.
var values = ['999MC111', '999MC', '999XYZ111']; // some test values
// does it end in digits?
!!values[0].match(/\d$/); // evaluates to true
!!values[1].match(/\d$/); // evaluates to false
To specify the exact number of tokens you must use brackets {}, so if you know that there are 2 alphabetic tokens you put {2}, if you know that there could be 0-4 digits you put {0,4}
^([0-9]{0,4})([a-zA-z]{2})([0-9]{0,4})$
The above RegEx evaluates as follows:
999MC ---> TRUE
999MC111 --> TRUE
999MAC111 ---> FALSE
MC ---> TRUE
The splitting of the expression into capturing groups is done by means of grouping subexpressions into parentheses
As you can see in the following link:
http://regexr.com?2vfhv
you obtain this:
3 capturing groups:
group 1: ([0-9]{0,4})
group 2: ([a-zA-z]{2})
group 3: ([0-9]{0,4})
The regex /^\d{1,4}[a-zA-Z]{2}\d{0,4}$/ matches a series of 1-4 digits, followed by a series of 2 alpha characters, followed by another series of 0-4 digits.
This regex: /^\d{1,4}[a-zA-Z]{2}$/ matches a series of 1-4 digits, followed only by 2 alpha characters.
Ok so I didnt really care about the middle 2 characters....all that really mattered was the 1st set of numbers and last set of numbers (if any).
So essentially I just needed to deal with digits. So I did this:
var lead = '123mc444'; //For example purposes
var regex = /(\d+)/g;
var result = (lead.match(regex));
var memID = result[0]; //First set of numbers is member id
if(result[1] != undefined) {
var leadID = result[1];
}

Piecing together a regular expression

I've asked a couple of JavaScript regular expression questions over the last few days as I try to piece together a larger regular expression but I am still having some trouble so I am going to ask about the entire problem, which is probably what I should have done in the first place.
Essentially, what I need is a regular expression that will match all of the following:
An empty string.
A string that contains at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
So some examples are as follows:
"" = true
"+" = false
"+abc" = true
"abc" = true
"+1" = false
"+12" = true
"+2" = true
Based on your stated requirements as amended, you want to match only:
An empty string, ^$
A string that contains at least one alpha-numeric character but does not start with a +1, ^(?!\+1).*[a-zA-Z0-9]
A string that starts with +1 and has at least 1 more alpha-numeric character, ^\+1.*[a-zA-Z0-9]
Put together, that is:
^$|^(?!\+1).*[a-zA-Z0-9]|^\+1.*[a-zA-Z0-9]
Or, if you like:
^($|(?!\+1).*[a-zA-Z0-9]|\+1.*[a-zA-Z0-9])
^(?:\+1[a-zA-Z0-9]+|(?!\+1).*[a-zA-Z0-9]+.*)?$
Explanation:
The regex is separated in two cases: ( CASE1 | CASE2 )
First case: \+1[a-zA-Z0-9]+ matches every text that starts with +1 and is followed by one or more alphanumeric char ([a-zA-Z0-9]+ stands for pick one or more chars that are either from a to z, from A to Z or from 0 to 9)
Second case: (?!\+1).*[a-zA-Z0-9]+.* matches every text that does NOT start with +1 ((?!\+1)), and is followed by as many characters you want as long as it contains at least one alphanumeric char (.*[a-zA-Z0-9]+.* stands for pick 0 or more of whatever char you want, plus the regex explained above, plus 0 or more of whatever char again)
These two cases respectively match your rules #3 and #2.
The rule #1 is taken care of by the ? at the end of the whole expression, meaning all of that is optional, therefore it can also be an empty string.
Please note some things such as:
(?:something) is used to match a string, but not capture it.
(?!something) is used to make sure it doesnt match a string
\ is used to escape special characters like + when you want them to stand as regular characters
+ is used to say one or more of the preceding item
* is used to say zero or more of the preceding item
Hope i helped!
Based on your most updated requirements:
An empty string.
A string that contains at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
Here is what I'd use:
/^([]|(\+1)?.*[a-zA-Z0-9]+.*)$/
In plan english, that regex says to look for a string that is:
Empty, or
Has an alphanumberic character (and optionally starts with +1 as well)
A string that contains at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
Let's rephrase this a little bit :
A string that has at least one alpha-numeric character but does not start with a +1.
A string that starts with +1 and has at least 1 more alpha-numeric character.
Try again :
but does not start with a +1 | A string that has at least one alpha-numeric character A string that starts with +1 | and has at least 1 more alpha-numeric character.
So what does this let us too?
Nothing. You just wanna match an empty string. I mean really ?
//var re = /(^$)/; //Matches empty
//var re = /(^[a-z0-9]+)/; //matches only string no plus
//var re = /(^\+([0a-z2-9])([a-z0-9].*)?)/; //Matches the + [not one] requirement
//Joined together with | for or
//Might be simplified more, but this works ;)
var re = /(^([a-z0-9]+.*|[a-z0-9]+.*|\+1[a-z0-9]+.*|\+([0a-z2-9])([a-z0-9].*)?)?$)/i;
function testIt( str, expected ) {
if( !!re.exec( str ) === expected ) {
console.info(str + "\tpassed" );
} else{
console.error(str + "\tfailed" );
}
}
testIt("", true);
testIt("+", false);
testIt("+abc", true);
testIt("abc", true);
testIt("+1", false);
testIt("+12", true);
testIt("+12_", true);
testIt("+2", true);
testIt("+2c", true);
testIt("+2_", false);
testIt("+007", true);
JSFiddle

Categories

Resources