Regex evaluate to true but its not supposed to [duplicate] - javascript

This question already has answers here:
Match exact string
(3 answers)
Closed 5 years ago.
I have input field which db is expecting to come as integer. if i type 60 it works fine, but 60.00 doesn't. I did RegExp for validation with the ^[0-9]+/ expession. It works fine for inputs like 60.asdass, 60.0320320, dasdasdas.60 etc. but if i type 60. and it evaluates to true and it passes the validation and i get an error from db. How can i make my regex to sets as false in this situation?

Add the end of string anchor ($):
^[0-9]+$

You could test the rest of the array as well and use start and end of the string as well for testing.
function check() {
var element =document.getElementById('input'),
value = element.value;
element.style.color = /^\d+(\.\d+)*$/.test(value) ? '#000000': '#ff0000';
}
<input id="input" type="text" onkeyup="check()">

You can use this. By using anchors it will fail if the full input is not the regular expression specified.
^\d+$

Related

Remove empty characters, blank characters, invisible characters in jQuery [duplicate]

This question already has answers here:
Remove not alphanumeric characters from string
(10 answers)
Regular expression to remove anything but alphabets and '[single quote]
(1 answer)
javascript regex to return letters only
(6 answers)
Ignoring invisible characters in RegEx
(2 answers)
Closed 2 years ago.
I am performing a validation in html text box which should pass only alphabets(a-z/A-Z) and few special characters like (*,& etc..). Otherwise it should show error some error.
I had written a JavaScript function which does the same.
function removeInvalidCharacters(selectedElement) {
if (selectedElement && typeof selectedElement.val() !== typeof undefined && selectedElement.val() != "") {
selectedElement.val(selectedElement.val().replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, "").replace(/\\f/g, "").replace(/%/g,""));
}
}
I am filtering selectedElement before passing to the function removeInvalidCharacters.
$("#name").val(toASCII($("#name").val()));
var selectedElement = $("#name").val();
But now I am facing a scenario in which empty characters, blank characters, invisible characters and whitespace characters are bypassing my regex. I could see some invisible characters are present in my name field. I want to replace these characters.
In further investigation I could found that Invisible characters - ASCII
characters mentioned in this link are the culprits. I need to have a regex to catch them and replace them.
Eg: AAAAAAAAAAAA‎AAAAAAAAAAA is the value in text field. Now if we check $("#name").val().length, it gives 24 ,even though we could see only 23 characters. I need to remove that hidden character.
Please help me with this scenario. Hope my query is clear
UPDATE:
var result = selectedElement.replace(/[\u200B-\u200D\uFEFF]/g, ''); fixed my problem.
Thank you all for the support.
If you want to allow only (a-z/A-Z) like you mention, try this:
str = str.replace(/[^a-zA-Z]/g, '');
Include the chars you want to keep instead of the ones you do not want, since that list may be incomplete
Otherwise look here: Remove zero-width space characters from a JavaScript string
const val = `AAAAAAAAAAAA‎AAAA**AAAAAAA`;
const cleaned = val.replace(/[^A-Za-z*]/g,"");
console.log(val.length,cleaned.length);

Getting a true or false reply to a Regex match? [duplicate]

This question already has answers here:
Return true/false for a matched/not matched regex
(5 answers)
Closed 3 years ago.
I'm trying to match an entire string against a regex formula. This is for validating if a phone number field is likely correct (just based on allowed characters, anyone can make up an number). I've played with Regex before but never truly understood the nuances that make it powerful.
Below I have my dummy phone number and I have the regex I'm using. As you can see I'm simply comparing the length of the match vs the length of the string and if they match the number must be valid.
Is there a way to get a simple true/false reply from a Regex check on an entire string?
var num = '+1 (888) 456-7896';
var regex = /[0-9+ ()-]*$/;
var found = num.match(regex);
console.log(found[0].length);
console.log(num.length);
You can use test()
var found = regex.test(num);

How do I insert something at a specific character with Regex in Javascript [duplicate]

This question already has answers here:
Simple javascript find and replace
(6 answers)
Closed 5 years ago.
I have string "foo?bar" and I want to insert "baz" at the ?. This ? may not always be at the 3 index, so I always want to insert something string at this ? char to get "foo?bazbar"
The String.protype.replace method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
If you expect the string "foo?bar?boo" to result in "foo?bazbar?boo" the above code works as-is
If you expect the string "foo?bar?boo" to result in "foo?bazbar?bazboo" you can change the call to .replace(/\?/g, '?baz')
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

Firefox Javascript: Remove non-numeric characters from input of type "number" - FF issue [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
the task looks simple. I have to remove non-numeric characters from an input field of type "number" on keyup in firefox.
The code:
$("#field").on("keyup", function() {
regex = /[\\D]+/;
$(this).val( $(this).val().replace(regex, '') );
});
Unfortunately as soon as a non-numeric character enters the field, its whole content gets replaced by the empty string.
For example:
234d = emptied > should be 234
Solution (here because the question has been closed):
This example works. I found out that it has to do with the field type. If the input in the field of type "number" contains non numeric characters, firefox shows the input but doesn't store it in the input object. As soon as I use a text input everything works fine. Seems to be a Firefox issue.
I think this question is NOT duplicate because it seems to regard a Firefox issue with input fields of type "number".
var val = '234d'.replace(/[^0-9]/g, '');
console.log(val);
var myString = '234d';
Try this line:
myString = myString.replace(/\D/g,'');
Reference:
strip non-numeric characters from string

Convert first letter of each word entered in a textbox to captial [duplicate]

This question already has answers here:
Capitalize input text in Javascript
(3 answers)
Trouble capitalizing first word in input with javascript/jquery
(2 answers)
Closed 9 years ago.
I have made a form for billing, but am having trouble converting the first letter entered in a text box to capital. I've looked around a bit, but couldn't find any luck.
Basically what I'm looking for is if possible the second I enter a letter into say first name text box it auto sets capital (if user forgets to capitalize) and then the rest are in lowercase.
If this is a visual need only, it can be done with css:
input {
text-transform:capitalize;
}
check this jsfiddle: http://jsfiddle.net/7zp6k/
this function should do it:
function capitalize(obj)
{
obj.value = obj.value.charAt(0).toUpperCase() + obj.value.slice(1);
}
html:
<input type='text' id='textfield' onkeyup='capitalize(this)'>
Here's another way.
Just use jQuery and a capitalize function.
Here is a working example.
$("#firstName").keyup(function(event) {
var tempVal = $("#firstName").val();
$("#firstName").val(capitaliseFirstLetter(tempVal));
});

Categories

Resources