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

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

Related

modify user input in javascript

I need to take a user input, in this case as a search word. But when sending this input to an API, the string must not contain any spaces. I tried .trim but this seems to only remove any spaces before and/or after the string. Essentially, I need to force any amount of words other than one together, any thoughts on how this could be achieved would be greatly appreciated.
function getSearch(){
var welcomeMsg = document.getElementById('result');
var search_term = document.getElementById('floatingInput');
<input type="text" class="form-control" id="floatingInput">
<input type="button" value="click">
<label for="floatingInput">Song title / artist name</label>
You can use String.prototype.replace() for this, for example:
> 'foo bar'.replace(' ', '')
'foobar'
If there are expected to be many spaces, you can use a global regular expression:
> 'foo bar baz otherfoo'.replace(/ /g, '')
'foobarbazotherfoo'
Finally, if you still want to see the word boundaries as suggested by #JoeKincognito, you can update the second argument from an empty space '' to the separator of your choice, for example:
> 'foo bar baz otherfoo'.replace(/ /g, '-')
'foo-bar-baz-otherfoo'
This will allow you to separate the search terms later if necessary, and will allow you to differentiate between users searching for e.g., butter and fingers from users searching for butterfingers
string.replace() method supports regex expression:
xxx.replace(/\s+/g, '') //xxx is an example string.
\s: matches any whitespace symbol

Accept decimal with comma and dot (html)

I need some help with this input because I want it only accept 2 decimals and comma or dot as well, but now just allow comma instead of a dot and any decimals. I'm extremely new with RegExp and I was trying with this.
<td>
<input type="number" ng-model="material.porcentaje" ng-change="calculaKilos(material, $index);validatePorcentaje($index)" id="porcentaje" class="input_small-stretch" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/">
</td>
Check out RegExr to help build your Regular Expression pattern. I could try to build the pattern for you, but without example text it is difficult.
You cannot add , to type="number". You need to change it to type="text" and then onkeyup you can check if there are any values other than numbers and comma you can replace it with ''
document.querySelector('input').addEventListener('keyup',(e)=>{
let value = e.target.value;
e.target.value = value.replace(/[^0-9.,]/g,'');;
})
<input type="text" ng-model="material.porcentaje" ng-change="calculaKilos(material, $index);validatePorcentaje($index)" id="porcentaje" class="input_small-stretch" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/">
Hope it will help

Js, How to ignore symbols that contribute text length in textbox?

My goal is to count text that are not symbols in textbox. For example, if user type in email_ex_3/2#mail.com the original length of the text is 21 but my goal is to ignore these symbols so the length become 16.
All I can think is using for loops to check these symbols, but I think it is very hideous.
JS
function test() {
alert(document.getElementById("firstText").value.length);
}
HTML
<input type="text" id="firstText" />
<button onclick="test()">Submit</button>
You could use a regular expression to replace all non-word characters with the empty string, and check the length of the result:
const getLen = str => str.replace(/[^A-Za-z0-9]/g, '').length;
console.log(getLen('email_ex_3/2#mail.com'));
You can use the replace method by passing a regular expression as the second argument.
function test(){
alert(document.getElementById("firstText").value.replace(/[^a-zA-Z 0-9]+/g, "").length);
}
<input type="text" id="firstText"/>
<button onclick="test()">Submit</button>
You can do this
function test()
{
alert(document.getElementById("firstText").value.replace(/[\W_]+/g, "").length);
}
(/[\W_]) exclude all non-alphanumeric characters and /g for saying all

username page javascript validation

Could anyone help with this?
Code allowing the user to input a username and a password, both of which must be validated as follows:
The username may only contain letters, dots (.), the at sign (#). The username must NOT be longer than 25 characters.
In order to limit to 25 characters, the easiest way is to use an
<input type="text" maxlength="25" />
In order to validate that input only contains letters, dots (.) and #, proceed with a regular expression.
Example:
<input id="input" type="text" maxlength="25" />
<button id="button">Test</button>
<br/>
<div id="validation" />
$(document).ready(function(){
var $text = $('#input');
var $btn = $('#button');
var $out = $('#validation');
$btn.on('click', _do_check);
function _do_check(e){
e.preventDefault();
e.stopPropagation();
var text = $text.val();
if (/^[a-zA-Z.#]+$/.test(text) ){
$out.html('OK');
} else {
$out.html('FAILURE');
}
}
});
Hope this helps.
Using only plain Javascript:
You will need to construct a regular expression. Check this to get an idea how it works in Javascript https://www.w3schools.com/jsref/jsref_obj_regexp.asp
The following expression would be a regular expression fitting your username requirements with the only allowed characters and the length restrictions at once
/^([a-zA-Z\.\#]{1,25})$/
You can play and learn how to build a regular expression with pages like https://regexr.com/
And as recommended you should start with some of your work in order to help actually with a problem and then the community can guide you to solve your real issue.

Javascript regExp Input Validation

This is my first post and i think the answer is very easy but i don't get it:
I (try) to build a shopify store but i have to make some modifications and here is the point at where i am stuck:
On my Product Page i want to inluce a <input type=text>, which is required, can only be Capital Letters and the length must min. be 1 and max. 10. I tried it with html5 pattern but it didn't worked. I read something, that if the shopify theme includes ajax, it just ignores the pattern and the required attribute (i don't know if this is true).
So i tried to make my own functions:
$('#dein-text').on("change textInput input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase();
});
});
this just should return the string into capital letters.
function checkText() {
var re = /(?=.*[A-Z]).{1,6}/;
if(re.test($('#dein-text').val())) {
$('#problem-bei-input').hide();
$('.add', $product).removeClass('disabled').removeAttr('disabled');
} else {
$('#problem-bei-input').show();
$('.add', $product).addClass('disabled').attr('disabled', 'disabled');
}
}
this function is executed at every change on the input form:
$('#dein-text').on("change textInput input", checkText);
This does not work, because it removes the disabled class if there is min. 1 letter (it does not check if there are more than 6) and if there is one capital letter (something like "HA11" does not add the (.disabled) class).
i hope i could describe what my problem is.
Thank you for your help!
edit: this is the .liquid code of the whole form:
https://codepen.io/shawdyy/pen/PmOPWy
(i hope you can see this on codepen, sry i am really new to the webdev thing)
You can try:
$('#my_id').on("change input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase().replace(/[^A-Z]/, "").replace(/^([A-Z]{1,10}).*$/g, "$1");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_id">
To only allow one to ten uppercase ASCII letters in the input field use the following HTML5 pattern:
<input type="text" pattern="[A-Z]{1,10}" title="Only 1 to 10 uppercase ASCII letters allowed!">
If you need to match a string that only contains 1 to 10 uppercase ASCII letters in plain JS, you need
 var re = /^[A-Z]{1,10}$/;
Note that start and end anchors (^ / $) are added by the HTML5 automatIically when using the regex in the pattern attribute.

Categories

Resources