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

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');
}

Related

How to limit the number of multiple characters in an input value?

I want to limit the number of letters at the beginning and end of the input value (e.g. QQ23F and SG21G) through JavaScript but I found that only one {} can be written in a pattern. Thanks for any help.
Here is my incorrect code:
var isValid = true;
var id=document.getElementById("pid").value;
if (!id.match(/[A-Za-z]{2}+[0-9]+[A-Za-z]{1}/)) {
document.getElementById("pidMessage").innerHTML="Your pid format is invalid!";
isValid = false;
}
You need to add the begging ^ and end $ signs
let isValid = true;
let id=document.getElementById("pid").value;
if (!id.match(/^([A-Za-z]{2}[0-9]+[A-Za-z]{1})$/)) {
document.getElementById("pidMessage").innerHTML="Your pid format is invalid!";
isValid = false;
}
And for everyone's sake use let not var

how to pass the json data inside javascript regex? and also validate password in sequence

I am trying to validate the password using javascript regex. Now I want to validate two lower case letters (2 small letters) which is coming from json.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password");
var lowerCaseLetters = /[a-z]{2}/g;
if(psw.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}
In the above code I am setting up a variable "Lcase" to json data and now I want to replace "{2}" (inside regex) with that variable "Lcase" coz the "Lcase" variable is dynamic. If I am doing something wrong then please guide me to come out of this problem.
I want to validate small case letters which is coming from json(dynamic number) to see how many small letters are there in the password string.
For your information the below code for password length is working.
if(psw.value.length >= jsonData.MINLEN_RANGE) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
If define your regular expression using RegExp, you can define {2} using Lcase.
This code also includes the question posted on the comments bellow.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password").value.replace(/([a-z])\d+/g, '$1');
var lowerCaseLetters = new RegExp('[a-z]{' + Lcase + '}', 'g')
if(psw.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}

Regular Expression in Javascript for password validation

I am trying to create a regular expression that validates a user's password when they create it. The password needs to be:
at least 6 characters long and can be any type of character
each character that is used needs to appear in the password exactly 3 times.
Good examples:
AAABBB
ABABBA
+++===
+ar++arra
myyymm
/Arrr/AA/
Does anyone know which regex would accomplish this?
You can ease yourself by sorting the password before testing it:
$('button').on('click', function(){
var s = $('#password').val();
var split = s.split("").sort().join("");
if(/^(?:(.)\1{2}(?!\1)){2,}$/.test(split))
console.log("Valid password");
else
console.log("Invalid password");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="password">
<button>Test me</button>
For 1st option you have to check without regex.
var str = "your password";
var pattern = /(.)(.*\1){3}/;
if(str.length >= 6){
// It will give you boolean as return
// If it is match then it return true else false
pattern.test(str);
}
An alternative solution since you're allowing code (which your question imply you wouldn't ;)
Using a function like verifyPass below should do the trick. It gradually replaces any valid three letter combination with an empty string. Checking that this is done in more than one iteration (it's at least 6 characters) and ending up with an empty string in the end, means it's a valid password.
function verifyPass(pass) {
var re = /^(.)((?:(?!\1).)*)\1((?:(?!\1).)*)\1((?:(?!\1).)*)$/,
cnt=0;
while(re.test(pass)) {
pass = pass.replace(re, '$2$3$4');
cnt++;
}
return pass==='' && cnt>1;
}
var testItems = [
'123123123',
'AAABBB',
'AAABBBAAA',
'Qwerty',
'ABABBA',
'+++===',
'111',
'qweqwd',
'sdcjhsdfkj',
'+ar++arra',
'mYYYmms',
'/Arrr/AA/'
];
testItems.forEach(function(item) {
document.write('<span style="color:' + (verifyPass(item) ? 'green' : 'red') + ';">' + item + '</span> <br/>');
});

jQuery Validating Australian Phone Numbers

I am trying to get the value from an input box, validate & format the number, then update the input field.
I want it to validate all Australian phone numbers (mobile and landline)
formatting mobile numbers to
04XX XXX XXX
and Landline numbers to
(0X) XXXX XXXX
var phone_number = $("#phone").val();
//validate mobile number
var formatted = phone_number.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
//replace number
$("#phone").val(formatted);
Any help would be awesome :)
You can use the same regex/replace logic you have suggested.
html
Mobile:<input id = "mobile" type = "tel" maxlength=8></input>
Landline:<input id = "landline" type = "tel" maxlength=10></input>
jquery
$("#mobile").blur(function(){
var mobile_ele = $("#mobile");
var mobileNum = mobile_ele.val();
var formattedNum = mobileNum.replace(/(\d{2})(\d{3})(\d{3})/g,"04$1 $2 $3");
mobile_ele.val(formattedNum);
});
$("#landline").blur(function(){
var landline_ele = $("#landline");
var landlineNum = mobile_ele.val();
var formattedNum = landlineNum.replace(/(\d{2})(\d{4})(\d{4})/g,"($1) $2 $3");
mobile_ele.val(formattedNum);
});
Demo:https://jsfiddle.net/7c0d418t/
I came up with 1 solution, not convinced how optimal it is, but someone may want to elaborate on it.
function validatePhoneNumber(phone_number){
var formatted = "";
//remove all non-digits
phone_number = phone_number.replace(/\D/g,'');
//if number starts with 61, replace 61 with 0
if (phone_number.match(/^61/)){
phone_number = "0"+phone_number.slice(2);
}
if (phone_number.match(/^04/)){
if (phone_number.length === 10){
var formatted = phone_number.replace(/(\d{4})(\d{3})(\d{3})/g,"$1 $2 $3");
} else {
alert('Invalid phone number');
}
} else if (phone_number.match(/^02|03|07|08/)){
if (phone_number.length === 10) {
var formatted = phone_number.replace(/(\d{2})(\d{4})(\d{4})/g,"($1) $2 $3");
} else {
alert('Invalid phone number');
}
} else if (phone_number.length === 8){
alert('Please use Area Code for landline numbers');
} else {
alert('Invalid phone number');
}
//update
$("#phone").val(formatted);
}
DEMO: https://jsfiddle.net/kb4u536a/
You can find here phone validation code for more than 200 countries: https://github.com/googlei18n/libphonenumber

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