What regex should i use to validate a number pattern? - javascript

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/)

Related

Regular expression to extract a 10 digit mobile number from string in javascript

I wish to validate if my input argument is a 10 digit phone number, even if there is additional text in the input.
I have tried this:
numbemail("my numberis 0987654321")
function numbemail(data){
var input =data;
var numb = new RegExp(
"\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s\\-.]?\\d{2,})+", "g"
);
var numbresult = input.match(numb);
if(numbresult){
var re=[]
if(numbresult[0].length === 10){
re.push(numbresult[0])
} else if(numbresult[0].length < 10) {
re.push(numbresult[0]+" ==>(WrongNumber: you provided Number is less than 10 digits)</p>")
} else if(numbresult[0].length > 10) {
re.push(numbresult[0]+" ==> (WrongNumber: you provided Number is more than 10 digits)</p>")
}
console.log(re)
}
}
When I tried this expecting 10 digits, but I got numbresult[0].length= 11
If I used a 10 digit string, then numbresult[0].length= 10
Expected Input:
input = ("my mobile number is 9087654321")
Expected Output:
"9087654321"
Try this one
var regex = /[\+]?\d{10}/
let strings = ['my numberis 0987654321', 'my number 8 is 9087654321', 'my number 8 is 9087654321123', 'my number 8 is 9087654']
strings.forEach(str => {
let output = str.match(regex)
if(output){
console.log('number is valid', output[0])
return
}
console.log('number is not valid - kindly enter 10 digit mobile number', output)
})
Try to make your RegExp more simple. You write too complex code for simple task.
let input = "my numberis 0987654321";
// filter symbols which can separate phone number dights
input = input.split(" ").join("").split("-").join("");
let phoneNumber = input.match(/\d{10,}/)[0];

Javascript RegEx validator

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.

check input value for specific format using Javascript

I have an input field that allows a user to enter a date.
I need this date to be in the following format: 10Jan13 (capitalization is not important)
There is a popup calender that if used will format the date correctly for the user.
I'd like to check the value of the input onblur using Javascript to be sure that the user did not either paste or type the date improperly.
I am currently checking number-only fields like this:
var numbers = /^[0-9]+$/;
if (!BIDInput.value.match(numbers))
{
checkedInput.value = "";
alert('Not a number');
}
and I'm checking letters-only fields like this:
var letters = /^[a-z]+$/
if (!nameInput.value.match(letters))
{
nameInput.value = "";
alert('Not a letter');
}
I would like to check the date format in a similar a fashion if possible. But anything that accomplishes the task will do. Can anyone point me in the right direction on how to get this done?
I know that client side validation does not replace server side validation. This is for user experience purposes only.
You're pretty much there with what you have. Basically your format is one or two digits, then one of 12 possible strings, followed by two digits. So for instance:
var shortDateRex = /^\d{1,2}(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\d{2}$/;
Breakdown:
^ Start of string.
\d{1,2} One or two digits.
(:?...) A non-capturing group. Or you could use a capture group if you like.
Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec An alternation, allowing any of those twelve choices. Naturally you can add more if you like. If you have two choices that start the same way (Jan and January, for instance), put the longer one earlier in the alternation.
\d{2} Two digits.
Side note: I'd have to recommend against two-digit dates on principle, and particularly given where in the century we currently are!
Responding to Amberlamps' comment that this doesn't validate the date: Once you've validated the format, it's trivial to then check the date itself if you like (to rule out 30Feb13, for instance):
var validateDateString = (function() {
var monthNames = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".toLowerCase().split("|");
var dateValidateRex = /^(\d{1,2})(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\d{2})$/i;
var arbitraryCenturyCutoff = 30;
function validateDateString(str) {
var match;
var day, month, year;
var dt;
match = dateValidateRex.exec(str);
if (!match) {
return false;
}
day = parseInt(match[1]);
month = monthNames.indexOf(match[2].toLowerCase()); // You may need a shim on very old browsers for Array#indexOf
year = parseInt(match[3], 10);
year += year > arbitraryCenturyCutoff ? 1900 : 2000;
dt = new Date(year, month, day);
if (dt.getDate() !== day ||
dt.getMonth() !== month ||
dt.getFullYear() !== year) {
// The input was invalid; we know because the date object
// had to adjust something
return false;
}
return true;
}
return validateDateString;
})();
...or something along those lines.
Live Example | Source
Or if (like me) you hate to see a list like that list of month names repeated you can use the RegExp constructor with a string instead, but you have to remember to duplicate your backslashes:
var monthNamesString = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
var monthNames = monthNamesString.toLowerCase().split("|");
var dateValidateRex = new RegExp("^(\\d{1,2})(" + monthNamesString + ")(\\d{2})$", "i");
Live Example | Source
You would use the following regular expression to check for a string starting with 2 numbers, followed by 3 characters followed by 2 numbers
[0-9]{2}[a-zA-Z]{3}[0-9]{2}

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.

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

Categories

Resources