String Replace with Regex Decimal Validation fails in Javascript - javascript

I tried to restrict the user input with string.replace using Regular expression. But it fails, its not allow to enter any character. Kindly see the following HTML Page.
<!DOCTYPE html>
<html>
<head>
<title>Decimal Validation</title>
</head>
<body>
<p>A function is triggered when the user is pressing a key and on keyup in the input field.</p>
<input type="text" maxlength="9" onkeyup="myFunction(this)">
<script>
function myFunction(text) {
if(text) {
text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})/g, '');
}
}
</script>
</body>
</html>
I need to allow only the digits and precision (i.e., allow only one dot). If the user input is only a whole number then the length should be 9 or if the input is only decimal part then allow maximum 8 precision or if the mixture then allow decimal(9,5) - allow 4 digit and 5 precision.
The above said regular expression fails to validate, allow the char only digits and only one period.

A validation and a replacement are two different tasks, you need to test the field first and after to replace with something eventually. Example:
function myFunction(text) {
if( !/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8})$/.test(text.value) ) {
text.value = ''; // or an other kind of replacement if you need something
// more precise
}
}
Note that you can also rewrite the pattern like this:
/^(?!\d*\.\d*\.)[\d.]{0,9}$/
To keep characters at the beginning that validate the pattern you can use this replacement:
text.value = text.value.replace(/^(\d{0,4}\.\d{0,5}|\d{0,9}|\.\d{0,8}).*/, '$1');

Related

How to enter whitespace only once after 4 characters in a string?

Hey I have a input where the user enters his social security number. To make the input more readable I want to insert a whitespace after the first 4 characters of the string. The social security number itself is 10 numbers long. So the result should looke like: 1234 567890. I only found solutions where a whitespace every 4 characters is inserted but no example which is similar to this. Has someone an idea how to solve this?
<input type="text" maxlength="10" #keyup="insertWhitespace()"/>
You can do this with the use of Regular Expression + HTML DOM Element addEventListener().
Reference Website For "Regular Expression": https://regexr.com/
With the help of a regular expression is a sequence of characters that specifies a search pattern in text or strings.
document.getElementById('example').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim();
});
<input id="example" maxlength="11" name="example" />
I think you should make your max length to 11 because white space also counts and try it with the following code
const ssn = document.querySelector("selector");
ssn.addEventListener("keyup",(e) => {
if(e.target.value.length === 4){
ssn.value += " "
}
})
Here is the solution (Javascript) to your problem:
The code below reads the input value and remove alphabets and then replaces the digit value with the appropriate space character only once as expected after 4 digits.
function insertWhitespace() {
document.getElementById('myElement').value = document.getElementById('myElement').value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim()
}
<input id="myElement" maxlength="11" onkeyup="insertWhitespace()" />

Regex one or two digit nubers sequences in input.val() [duplicate]

I have a text area and a user can input US zip codes in it separated by a comma or (comma and space).
It could be like
12345,45678, 89654
The following regex is working and is removing not allowed characters:
$object.val($object.val().replace(/[^\d\, ]/g, ''));
I would like to enhance it, so that
i always should have 5 digits in the beginning
after 5 digits, there should be a comma or comma and space
comma or (comma and space) should not be at the very end of the string. It must be 5 digit number at the end.
This needs to tackle the copy paste as well. The user may copy paste invalid length for the zip code.
Thanks
Use this regex:
^\d{5}(, ?\d{5})*$
It specifies 5 digits at the beginning: ^\d{5}
and any number of other comma, space, and 5 digit combinations: (, ?\d{5})*
You can use:
var s='12345,45678, 12345';
var m = s.match(/^(?:\d{5},\s?)*\d{5}$/);
<html>
<head>
<title></title>
<script type="text/javascript">
function Validate(txt) {
txt.value = txt.value.replace(/[^, 0-9]+/g, '');
}
</script>
</head>
<body>
<form>
<input type = "text" id ="txt" onkeyup = "Validate(this)" />
</form>
</body>
</html>

Add hashtag before each keyword

I am a newbie in coding JS and hope someone can guide me to the right direction of my keyword system. Below are the requirements for keyword text field's behavior.
Only non-symbol character (includes letter, digit and other countries' languages) and space are allowed. If any symbols are entered, it should be replaced by '' / the input text will not display the symbols.
the hash (#) should be added instantly when the first non-symbol character of keyword is entered.
the keyword is separated by a space
Below are my codes:
function hashtag() {
str = document.getElementById('tagid').value;
tagged = str.replace(/#/g, '').replace(/([a-zA-Z0-9]+)/g, '#' + '$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword:
<input type="text" name="tag" id="tagid" onkeypress="hashtag();" />
The problem are, the hash (#) can only be added when I entered the second non-symbol character / a space, but not the first one. And, there is no handling for symbols' input and no hash added before other countries languages.
Thanks in advance!
Here's a snippet that should work. My changes are:
Use onkeydown instead of onkeyup to trigger the function. onkeydown fires before the letter has been inserted into the text field and so the function doesn't see the key you just typed.
Use [^a-zA-Z0-9]/g as the regex. ^ means "anything but", so basically you're removing everything except the characters listed there. You could also use [^\w]/g but that would also allow the underscore which may or may not want.
Add an extra step to preappend the # because the above step removes it. (may seem wasteful but it's elegant and plenty fast enough)
function hashtag() {
//get the current contents of the text field
var str = document.getElementById('tagid').value;
//strip any non-word characters (will also strip hash symbol)
str = str.replace(/[^a-zA-Z0-9]/g, '');
//add the hash symbol back
str = '#' + str;
//update the text field
document.getElementById('tagid').value = str;
}
Enter keyword:
<input type="text" name="tag" id="tagid" onkeyup="hashtag();" />
For the first issue of the hash only being applied on the second press, you can use onkeyup="hashtag();" to execute the action after the keypress, once the text has been added to the input field and can then be evaluated.
Here is some documentation on JavaScript keypress events that may be helpful.
For removing symbols whilst still allowing foreign characters, I couldn't find anything great in pure js (PHP has ways to work around this which is interesting), so I've taken a different route of deleting all excluded characters (hopefully, if there's more please edit in to make more complete) and then "hash-tagging" everything else that isn't a space.
This would leave you with a function like this:
function hashtag() {
str = document.getElementById('tagid').value;
str = str.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.##£\/]/g, '');
tagged = str.replace(/#/g, '').replace(/([^" "]+)/g, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Here's the complete code that you can run within the answer:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HashTag</title>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function hashtag() {
str = document.getElementById('tagid').value;
str = str.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.##£\/]/g, '');
tagged = str.replace(/#/g, '').replace(/([^" "]+)/g, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
</script>
</head>
<body>
Enter keyword: <INPUT TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"></input>
</body>
</html>
bind to onkeyup event
replace [a-zA-Z0-9]+ by \w+
for foreign symbols, you will have to add them one by one (I tried to put as many as I could find):
I added the i flag for your regex, you won't have to worry about uppercase letters like 'Â' as long as you have the lower case one
function hashtag() {
str = document.getElementById('tagid').value;
tagged = str.replace(/#/g, '').replace(/([\wâàãäéèêëîìôòõòùûüñ]+)/gi, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword: <input TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"/>
Edit :
not sure if you want to keep or remove special characters, here is a version were special chars are removed :
function hashtag() {
str = document.getElementById('tagid').value;
// remove things
str = str.replace(/[^\w ]/g, '');
tagged = str.replace(/(\w+)/gi, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword: <input TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"/>

Validation for special characters not working

This is my code
<!DOCTYPE html>
<html>
<script>
function isSpclChar() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
if (document.getElementById('edit_tagline').value.indexOf(iChars) != -1) {
alert("The box has special characters. ");
} else {
alert("No special character");
}
}
</script>
<body>
<input type="text" id="edit_tagline" onblur="isSpclChar()">
</body>
</html>
My first question why this validation is not working?
My second question is can anybody explain me the meaning of this line
if(document.getElementById('edit_tagline').value.indexOf(iChars) != -1)
because I am new to JavaScript and copy paste the code from somewhere I don't know it's working.
So kindly if anyone could explain me the working of this code?
iChars is't a character range, it's treating it as a single word. You're going to need to implement a regular expression in order to do this.
Here's a working example of some validation in javascript, leveraging jQuery for brevity. Hopefully you can get it working in your context. I took the liberty of using alphabet characters and negating the expression, vs. writing out all of the potential special characters (there are hundreds including unicode ranges!).
$('button').click(function () {
if (!(/^[a-zA-Z0-9]+$/i).test($('#edit_tagline').val())) {
alert("The box has special characters. ");
} else {
alert("No special character");
}
});
HTML:
<input type="text" id="edit_tagline">
<button>Test</button>
Working example: http://jsfiddle.net/remus/9jwGW/
If you're not familiar with regular expressions, best read up on how those work (and check out http://regex101.com) before you get much further.

Javascript Textbox "Scrubber"

I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.
I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be entered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.
<script type="text/javascript">
function scrub(text) {
var commands = new Array{"someCommand","anotherCommand",...};
for (var i = 0; i <= commands.length; i++) {
if (text.value.toLowerCase().equals(commands[i])) {
//command is valid; do something here
} else {
alert("Invalid command");
}
}
text.value = ""; //clears the text box
}
</script>
For your textarea do this:
<textarea onblur="scrub(this);" ...></textarea>
Is there a set of keywords? And can be they be combined only in a certain fashion?
Looks like couple of regex patterns will be able to do the trick.
e.g: to match "9030 OUT FU [1234 TEST]" regex would be: /\d{4} OUT FU \[\d{4}\]/.
OUT FU and can be substituted with \w{3} and \w{2} respectively (unless you do not want any word to be allowed).
Use regular expressions.
html:
<input type="text" id="code" />
<input type="button" value="test" onclick="alert(checkCode())" />
javascript:
function checkCode(){
var code = document.getElementById('code').value;
return code.match(/\d+ \w+ \w+ \[\d+ \w+\]/)!=null ? true : false;
}
http://gskinner.com/RegExr/ is very helpful with regular expressions.
When you say "exactly this format", you have to understand that we have no clue what you mean. There are an infinite number of patterns that could be used to describe your example. The regular expression above will match if the code has a string of numbers, then a word, then another word, then an opening bracket, then a string of numbers, then a word, then a closing bracket.

Categories

Resources