Javascript RegEx validator - javascript

I need to validate control in Javascript.
the number has to be max 12 numbers where first 7 letters are 9900000 then 0 or 1, and rest 4 numbers are free.
I already defined validator as:
var validator = new RegExp("/^9900000[0-1]{3}\[0-9]{4}/");
but it doesnt work, what's wrong?
EDIT:
var check = 990000014212;
var validator = new RegExp("/^9900000[0-1][0-9]{4}$/");
console.log(validator.test(check));
if (validator.test(check))
{
console.log("Valid");
}
else
{
console.log(check);
console.log("Invalid");
}
How it is possible that the result is always "Invalid", and false?

You have a {3} in your RegExp string, which conflicts with your description.

Related

Searching keywords in JavaScript

Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"

What regex should i use to validate a number pattern?

For this first validate I try to validate an input of 4 digits, however when i try to run it and enter 4 digits the error still shows up:
function pCodeValidate() {
var pCode = document.getElementById("postcode");
var pCodePattern = /^\d{4}$/;
if (!(pCodePattern.test(pCode))){
errorList("post code must be 4 digits")
}
//return
}
The second one validates a mobile number with the pattern "04dddddddd, where d is a digit". this is my code:
function mNumberValidate() {
var mNumber = document.getElementById("mobilenumber");
var mNumberPattern = /^\d{10}$/;
if (!(mNumberPattern.test(mNumber))){
errorList("invalid mobile number");
}
//return
}
For this second part what regex should I use to enforce "04" being the first value in the input?
The problem with your first function is that you are not using the regex to test the value of the input, you are trying to test a reference to the input itself. Change the following line:
var pCode = document.getElementById("postcode");
to get the value:
var pCode = document.getElementById("postcode").value;
In your second function you have the same problem, which you'd fix the same way:
var mNumber = document.getElementById("mobilenumber").value;
// --------------------------------- add this part >-^^^^^^
Then the regex you need for a phone number starting with 04 is as follows:
/^04\d{8}$/
That is:
^ - beginning of string
04 - the literal characters "04"
\d{8} - any 8 digits
$ - end of string
(Dodgy demo: https://jsfiddle.net/xah6qstz/)

Regex: Check if string contains SSN in any part of the string

Can any one tell how to check if a String contains a social security number (SSN) using REGEX
Example data:
(1): my ssn is 123-44-8686
validate this ==> Need to return as true, since it contains a number in SSN format (XXX-XX-XXXX)
(2) my ssn is nothing ==> Need to return as false, since it does not contain a number in SSN format
No need to use REGEX.
Hopefully Something like this will work
var str = "123-44-8686";
var res = str.split("-");
if(res.length == 3){
var ssn1=res[0];
if(ssn1.length==3){
var ssn2=res[1];
if(ssn2.length==2){
var ssn3=res[2];
if(ssn3.length==4){
alert("valid formate");
}
}
}
}
else{
alert('Invalid formate');
}

regex for money values in JavaScript

Been out of the regex game for a while. Trying to come up with something that will allow the user to enter a money value either with/without dollar sign or with/without commas. For example, all the of the following values should be valid:
5
5.1
5.10
$5
500,000
500,000.1
500,000.10
$100,000,000.50
etc....
Could someone please help me out?
This should work:
isValid = str.search(/^\$?[\d,]+(\.\d*)?$/) >= 0;
A little more strict with comma placement (would reject 3,2.10, for example):
isValid = str.search(/^\$?\d+(,\d{3})*(\.\d*)?$/) >= 0;
To get a number out of it:
if(isValid) {
var num = Number(str.replace(/[\$,]/g, ''));
...
}
I didn't Test Driven Developement, TDD, for this one using the Qunit framework.
TDD overview http://net.tutsplus.com/tutorials/javascript-ajax/test-driven-javascript-development-in-practice/
1st: Write tests.
2nd: Watch tests fail.
3rd: Make test pass.
4th: Refactor.
var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
test("test money format for valid values", function () {
var moneyArr = ["5","5.1","5.10","$5","500,000","500,000.1","500,000.10","$100,000,000.50", "500,000,100" ];
var i = moneyArr.length;
while( i-- ){
equal( moneyTest_RE.test( moneyArr[ i ] ), true, moneyArr[ i ] + " didn't match completely." );
}
});
test("test money format for invalid values", function () {
var moneyArr = ["5..","$$5.1",".5.10","$5.2.","50,0,000",",500,000.1","500,000,10,","$1,00,000,000.50", "500,000,10"];
var i = moneyArr.length;
while( i-- ){
equal( moneyTest_RE.test( moneyArr[ i ] ), false, moneyArr[ i ] + " didn't match completely." );
}
});
Here's one possible solution to your problem.
var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
Demo here: http://jsfiddle.net/vpyV6/
I forgot to refactor though.
^(\$?\d{1,3}(?:,?\d{3})*(?:\.\d{2})?|\.\d{2})?$
This one took a while, but I finally got something fully functional. It allows for cases such as 100.00, .35, $1.35, etc. While excluding entries with misplaced commas, too many numbers in between or before commas, or too many numbers after the decimal point.
You can play around with it here
var currencyRegex = /^[$£€]\d+(?:\.\d\d)*$/g;
Example: $10 or £10 0r €10 but if you use simple 10 this will be wrong
Perhaps this?
http://refiddle.com/2tg
(\$?(:?\d+,?.?)+)
Also, http://refiddle.com/2ti ; a longer version that doesn't match numbers like 123,45.4.3
^(\$?(:?\d+,?)+(?:.?\d+)?)$

Extract substring out of a user input phone number using Javascript

I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(phoneRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
Its working very fine but the problem is that
EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.
Can some one guide me with some example how to do this task.
Thank you
Set the element's onblur method a callback as follows:
var isValidPhoneNumber = function(string) {
...
}
var reformat = function(string) {
/*
* > reformat('example 123 1 1 2 3 123-45')
* "+123-1-123-1234"
*/
var numbers = string.match(/\d/g);
return '+' + [
numbers.slice(0,3).join(''),
numbers.slice(3,4).join(''),
numbers.slice(4,7).join(''),
numbers.slice(7,11).join('')
].join('-');
}
var reformatPhoneNumber = function() {
var inputElement = this;
var value = inputElement.value;
if (isValidPhoneNumber(value))
inputElement.value = reformat(inputElement.value);
else
// complain to user
}
Here are two example ways you could set the onblur callback handler:
document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>
You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.
To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:
function isPlusAndEleventDigits(string) {
/*
* Returns whether string is exactly of the form '+00000000000'
* where 0 means any digit 0-9
*/
return string.match(/^\+\d{11}$/)!==null
}
Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");
Then do next procedure.

Categories

Resources