Javascript strip after X characters prior to form submit - javascript

UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?

Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));

Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).

Related

How to remove characters when input not matches regex in JS

<input id="myInput" onblur="myFunction()">
<script>
function myFunction() {
var value= document.getElementById('myInput').value;
var regexCharacter = /[0-9|,]+/g;
strFirst = value.replace(regexCharacter, '')
document.getElementById('myInput').value = strFirst
}
</script>
I want to replace '' when the input does not match the regex's.
My regex just allow input number and comma.
My function is replace when input matching, i want to replace when it's not matching.
E.g a12,b2a => 12,2
can anyone help me, thanks.
Use /[^0-9|,]+/g as your regex. The ^ mark is used to match any character that's not in range.
Pro tip: You dont have to memorize all these tokens, just use a tool like https://regex101.com/
First of all, your function is not called to check the value with reqex.
then yout reqex replace "" when is number not charactors
<input type="text" id="myInput">
<script>
myInput.addEventListener("input", function (e) {
var value= document.getElementById('myInput').value;
strFirst = value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1')
document.getElementById('myInput').value = strFirst
});
</script>
in this code you can write number whith dot
whith this reqex
value.replace(/[^0-9.]/g, '').replace(/(..?)../g
I think you should edit your regex to match letters instead of numbers. Like this: /[a-zA-Z|]+/g

Regex Javascript block Input

i've just build a javascript function with a regex control that allows 3 numbers and one dot.
function restrictNumber(e) {
var newValue = this.value.replace(new RegExp(/^(?!^(?:\d{1,3}|\d(?:\d?\.\d?|\.\d{2}))$).*/, 'gm'), "");
this.value = newValue;
}
$('.decimal').on('input', restrictNumber);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">
The specs of the regex are:
max. 3 numbers
only one or no dot
dot can be anywhere
Here is a regex demo for it: https://regex101.com/r/3Ru1O3/3/
i tried to "block" the input when a char is put in that isn't fitting. But when i try to test it deletes my hole string.
How can i change that behaviour that i just can't set new numbers put the string isnt vanishing.
You didn't say much about your actual requirements, as in, if the decimal is required at a certain place value, etc.. but based on what your existing regex does, it could definitely be shortened.
function restrictNumber(e) {
var newValue = this.value.replace(/[^\d\.]/, "").substr(0,4);
this.value = newValue;
}
$('.decimal').on('input', restrictNumber);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">

How can I add a comma after each 3 digits?

This is simplified of my code:
$("#annual_sales").on('keyup', function () {
$(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
I'm trying to add a comma after every 3 digits.
The patterns works well here, but as you can see (in the code snippet above) it doesn't work in the JS. Any idea what's wrong?
Presumably, you want these commas added from the right as a US-style number separator. This code will do that by reversing before and after adding the commas.
var addCommas = s => s.split('').reverse().join('')
.replace(/(\d{3})/g, '$1,').replace(/\,$/, '')
.split('').reverse().join('') // Really want String.prototype.revese!
$("#annual_sales").on('keyup', function () {
$(this).val( addCommas($(this).val().replace(/\,/g, '')) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
(Doing the reverses by converting to an array really makes me want a String.prototype.reverse method.)
If you have to support numbers with more than two decimal places, there would have to be additional work on this function.
Doesn't work here since the event fire multiple time, then you need to remove the previous added comma's first every time the event fired and add new ones in the desired positions :
$(this).val().replace(/,/g,'').replace(/(\d{3})/g, "$1,")
** NOTE:** I suggest the use of input event instead since it's more efficient when tracking the use inputs, also you could adjust the regex so the comma will not be added at the end of the line :
/(\d{3}(?!$))/g
$("#annual_sales").on('input', function() {
$(this).val($(this).val().replace(/,/g, '').replace(/(\d{3}(?!$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
In your current pattern (\d{3}) you add a comma after matching 3 digits and also when there is already a comma following the 3 digits.
What you might do is match 3 digits using a negative lookahead (?!,) to assert what follows is not a comma:
(\d{3}(?!,))
$("#annual_sales").on('keyup', function() {
$(this).val($(this).val().replace(/(\d{3}(?!,))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
If you don't want the comma at the end of the line you could use an alternation in the negative lookahead that asserts what follows is neither a comma or the end of the line (\d{3}(?!,|$))
$("#annual_sales").on('keyup', function() {
$(this).val($(this).val().replace(/(\d{3}(?!,|$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
You need to strip the previously added "," from the value on beforehand like below.
$("#annual_sales").on('keyup', function () {
$(this).val($(this).val().replace(new RegExp(",", "g"), ""));
$(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
Honestly, I think the best and most straightforward way to accomplish this is not to rely on directly using regex substitution to add a comma. Because regular expressions run from left to right, and in this case we want to parse from right to left, there's really no easy way to do this.
Instead, I would recommend using javascript to do the heavy lifting:
$("#annual_sales").on('keyup', function () {
var value = $(this).val();
var match = value.match(/[0-9,.$]+/); // Match any chars seen in currency
var new_value = "";
if (match) {
var digits = match[0].match(/\d/g); // Match single digits into an array
if (digits.length > 3) {
for (var i = digits.length - 3; i > 0; i = i - 3) {
// Start at 3 less than the length,
// continue until we reach the beginning,
// step down at intervals of 3
digits.splice(i, 0, ","); // Insert a comma
}
new_value = digits.join("");
$(this).val(new_value);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
With this function, you could expand its handling of currency values, such as prepending the value with a dollar sign, or also splitting on a decimal point and forcing two digits following it.
Edit: Scott's answer is a much shorter version of what I am suggesting here (very nice, by the way).
Well, you coul've just use this simple trick :
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return ' ' + label + ' : ' + value.replace(/(.)(?=(.{3})+$)/g,"$1,");
}
}
}

regex jquery for IDnumber if match then enable button

i don't know much regex so if some one can help me with this it would be great i have a input box and a button.
if the user enters A12345678 the first character should always be A and the rest should always be numbers and altogether it should have less then 10 characters
<input type="textbox" id="id" />
<input type="submit" id="submit" />
<script type="text/javascript">
/*Check if ID is correct */
$('#id').keyup(function(){
var id= $(this).val();
if(id == /*'A12345678' */{
//enable button
}else{
// disable button
});
</script>
i would appreciate if some one could help me out a bit with this
Here ya go ^(A\d{1,9})$;
^ will start the verification at the beginning of the string
() encapsulates your result. not necessarily needed, but I like to have them
A will match the uppercase character
\d{1, 9} will match 1 to 9 numbers following the letter A
$means the end of the string
Use:
if(id.match(/^(A\d{1,9})$/)) {
// do stuff
}
Hope this helps.
Watch it work: https://jsfiddle.net/ppmr12v6/

Allow Only Numbers and a Dot in the following Format with Regex javascript/jquery

I have an input field which should get filled by the user with only numbers and a singel dot/comma and only in the following format. This should occure .on("input") meaning as the user types it should secure the right input format.
A wrong char should be replaced with a blank.
Format Example: 1.000 1.281 21212.000 21212.810Nothing like this:1.02.12 or 1919,201,00 Only a dot between the two Number blocks.
This is what i have so far:
Regex 1:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[^0-9]/g,'');
});
Regex 2:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
Regex 3:
$("body").on("input", "#testId", function(){
this.value = this.value.replace(/[0-9]+\.+[0-9]{1,3}/g,'');
});
I think i am doing something wrong with the replace() method.
Unfortunately none of them work as i want to. Any help is appreciated.
Here is the FIDDLE
Should Work in IE11
You can try this. make sure your input type is tel which will allow you to have numeric keypad in mobile browser
const regex = /[^\d.]|\.(?=.*\.)/g;
const subst=``;
$('#testId').keyup(function(){
const str=this.value;
const result = str.replace(regex, subst);
this.value=result;
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<input id="testId" type="tel" />
</body>
</html>
try this one,
^[0-9]*(\.|,)?[0-9]*$
this take below cases:
1111,
.0000
123,12
12.12
12345
but if you want only
111,11
11.11
12345
so please use this
^[0-9]+(\.|,)?[0-9]+$
to force use dot/comma please use this
^[0-9]+(\.|,)[0-9]+$
add this code
$("#testId").keyup(function(){
var vals = $("#testId").val();
if(/^[0-9]*(\.|,)?[0-9]*$/g.test(vals))
$("#testId").val(vals);
else
vals = vals.replace(/.$/,"");
$("#testId").val(vals);
});
and change input type to
type="text"

Categories