Regular expression for numbers only - javascript

I am using the following code to detect if a string is a number:
var numberPattern = /[a-zA-Z]/;
if (!numberPattern.test($(this).text())) {
numberSort = true;
} else {
numberSort = false;
return numberSort;
}
But i have something like "(123)" and it detects it as number. Can somebody help me to update the regex to detect the paranthesys too?
I have tried: /[a-zA-Z]/(/)/ but does not work.

Use \d for matching digit and start and end anchors to check entire string.
var numberPattern = /^\d+$/;
return numberPattern.test($(this).text());

Related

Regular expression to count characters after coma

How can I build a regular expression that will replace each comma with a '.' decimal point if there are more than 3 or less than 3 digits.
that is 4,444 is correct and stay like that but 3,33 will be 3.33 or 4,4444 will be 4.444
similarly it can be like this as well 1,234,45,6789, and it should become 1,234.45.6789
function commaToDot(number) {
let regex = /^\d{1,3}(?:\,\d{3})*((?:,\d+)+)*?$/;
let matches = number.match(regex);
if (matches[1]) {
number = number.replace(matches[1], matches[1].replace(/,/g, '.'))
}
return number;
}
console.log(commaToDot('4,4444'));
console.log(commaToDot('5,555'));
console.log(commaToDot('3,33'));
console.log(commaToDot('1,234,45,6789'));
console.log(commaToDot('1,234,45,678,9'));
console.log(commaToDot('5,5,5,5,5'));
This will match everything after the numbers stop being part of the \d{1,3},\d{3} pattern, and replace their commas with dots.
From what I gather, this is what you are looking for.
Edit
After leaving my comment above to check validity of "1,333.22,333", I've had to re-write the regex slightly:
function commaToDot(number) {
let regex = /(?!,\d{3},)(,\d{0,2})|(,\d{4,})/g,
matches = number.match(regex);
if (matches) {
matches.forEach((match) => {
number = number.replace(match, match.replace(/,/g, '.'));
});
}
return number
}
console.log(commaToDot('1,234,45,678,9'));
console.log(commaToDot('4,4444'));
console.log(commaToDot('5,555'));
console.log(commaToDot('3,33'));
console.log(commaToDot('1,234,45,6789'));
console.log(commaToDot('5,5,5,5,5'));
console.log(commaToDot('12,345,678,90'));
This should now do what you would like it to do.
With RegExp.test() function and specific regex patterns:
var commaToDot = function(str){
if (/^-?\d+[,\d]+\d+$/.test(str) && /\d+,(\d{1,2}|\d{4,})\b/.test(str)){
var parts = str.split(',');
return parts.length > 2? parts[0] +','+ parts.slice(1).join('.') : parts.join('.');
} else {
return str;
}
};
console.log(commaToDot('4,4444'));
console.log(commaToDot('5,555'));
console.log(commaToDot('3,33'));
console.log(commaToDot('1,234,45,6789'));

Javascript regex doesn't give error message when it should

I try to input the following value "f+11111111111", and my code doesn't display error message. I tried to remove regex2 condition, and then it worked. But how come? It's an AND condition, why does it act like it's an OR operator?
function validatePhone()
{
var phone = document.getElementById("phone").value;
var regex1 =/^[\+\d][\s(\-\d][\s()\-\d]{8,}/g;
var regex2 = /\D*(\d\D*){11}/g;
if (!phone.match(regex1) && !phone.match(regex2)) {
producePrompt("Error", "comment_phone_prompt");
return false;
}
}
function producePrompt(message, promptLocation)
{
document.getElementById(promptLocation).innerHTML = message;
}
Your second regular expression /\D*(\d\D*){11}/g matches the given string f+11111111111 and therefore the whole condition evaluates to false. You can visualise your regular expressions using regexper.com.
I'm not sure what you're trying to do but mind that even this string is matched by the second regex: 'f+1dsadsadasda123131231dsdadai-094i-)#)#(#)_(#_!' Is this what you want?
Second regex matches everything. Single regex is enough.
function validatePhone() {
var phone = document.getElementById("phone").value;
var regex1 = /^(\+\d)?(\(|-)?\d{3}(\)|-)?\d{3}-?\d{4}$/;
//match +1-800-123-45678, (555)123-4567, and so on
if (!regex1.test(phone)){
producePrompt("Error", "comment_phone_prompt");
return false;
}
return true;//both sides should return
}

how to replace a string which is not integer using regex in javascript

i have use this regex try to replace a string which is not a integer ,however it replace when it is a integer.
this.v=function(){this.value=this.value.replace(/^(-?[1-9]\d*|0)$/,'');}
what is the opposite regex? :what is the regex for replace a string which is not a integer with "".
eg:if user entered string is not -2,0,1,123 such like that i want clear the input.if string like 2e3r,2.5,-1.3 the input will be clear
value
If you must use regex then the following should work. Not tested for efficiency, just thrown together.
var numbersOnly = function(number_string) {
var re = /(\+?|\-?)([0-9]+)(\.[0-9]+)*/g;
return number_string.match(re);
}
numbersOnly('pears1.3apples3.2chinesefood-7.8');
// [ '1.3', '3.2', '-7.8' ]
i have solved this one by changing the function logic:
onblur="(this.v=function(){var re=/^(-?[1-9]\d*|0)$/;if(!re.test(this.value)){this.value=''}}).call(this)
You could sanitize user input using parseInt or Number methods. For example:
var normalInput = "1";
normalInput = parseInt(normalInput, 10);
console.log(normalInput); // prints 1
var wrongInput = "12a23-24";
wrongInput = parseInt(wrongInput, 10);
console.log(wrongInput); // prints 12 (stops after first not valid number)
Or something like that:
var myInput = "21312312321",
processedInput = Number(myInput);
if(processedInput !== NaN){ // if number given is a valid number return it (also works for float input)
console.log(processedInput);
return processedInput;
}
else{ // otherwise return an empty string
return "";
}
Jsfiddle example1 example2.
To remove all non-digit characters in the string:
this.v=function(){this.value=this.value.replace(/\D+/g,'');}

i want that the first two characters of my string should not be special characters

I want that the first two characters of my string should not be special characters
function detectInvalidChars(limitField)
{
var len=limitField.value.length;
var char1=limitField.value.substring(0,1);
var char2=limitField.value.substring(1,2);
if(char1=='&'||char1=='<' char1=='!' || char2=='&'||char2=='<'..........so on)
{
alert("Invalid character");
limitField.value = limitField.value.substring(0,len-1);
}
}
instead of matching the char1 and char2 with each special character. What can I do?
You can use a regular expression:
var re = /^([&<!]|.[&<!])/;
if (re.test(limitField.value)) {
alert...
}
look into the string method .charCodeAt(n)
you should be able to then compare the ascii values in ranges.
so for example if you want to exclude control charactercs you could write something like
if (mystring.charCodeAt(0)<32 || mystring.charCodeAt(1)<32) {
alert("Invalid character");
}
or use a regex.
You may find this question helpful:
isalpha replacement for JavaScript?
You can use regex for that on a substring of the original.
substring gets the part of the string from "from" to "to".
/^[0-9a-z]+$/ is regex that allows only 0 ... 9 and a ... z
function is_part_alnum(value, from, to)
substring = value.substring(from, to);
if(!substring.match(/^[0-9a-z]+$/) {
alert("Invalid character(s)");
}
}
If you don't want to use regex and want to define your own set of special characters, you could use a function like this:
function detectInvalidChars(s, count) {
var specialChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?~_";
var firstChars = s.substr(0, count).split('');
for(var i=0; i<firstChars.length; i++) {
if(specialChars.indexOf(firstChars[i]) !== -1) {
// invalid char detected
}
}
}
Where s is your string and count is the number of the first characters that should be investigated.

javascript code to check special characters

I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < chkfile.value.length; i++)
{
if (iChars.indexOf(chkfile.value.charAt(i)) != -1)
{
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
Suppose I want to upload a file desktop.zip from any Linux/Windows machine.
The value of chkfile.value is desktop.zip in Firefox, but in Chrome the value of chkfile.value is c://fakepath/desktop.zip. How do I get rid of c://fakepath/ from chkfile.value?
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Try This one.
function containsSpecialCharacters(str){
var regex = /[ !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
return regex.test(str);
}
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}

Categories

Resources