Regular Expression - +/- sign and decimal - javascript

I am trying to create a regular expression for decimal number and at the same time "-" or "+" sign to be optional at the start.
There are a lot of information about this, so I finished with this:
/^[+-]?\d+(\.\d+)?$/
So, I have tested this in the console using the test() function and it is working perfectly.
My question is more about where to do this check:
if the check is on keypress event I am able to use preventDefault() in order to "consume" the incorrect symbols but I am retrieving the text like this and have no access to the last entered symbol - $(event.target).val()
if the check is on keyup event I have access to the whole text, but I am not able to remove the incorrect symbol, because I do not know which is it, and where it was put in (using the mouse it can be put in the start or in the middle of a valid string)
I need to check combination of symbols, not validate the symbols only. For example:
- //invalid
- 1 //valid
1. //invalid
1.2 //valid
So, I guess I should the check when the whole sting is entered, but then, how two remove the incorrect characters? Removing the whole string on when it is invalid does not look right.

The below is one possible way to tell the user if there is anything wrong with their input as they keep entering. Click here for a sample demo.
In addition, we can also add a <div> listing the allowed characters/format. This in addition to letting the user know that there is something wrong, will also tell them what forms a valid input.
HTML:
<input id='ip' type='text'/>
JS:
var regex = new RegExp(/^[+-]?\s*\d+(\.\d+)?$/);
document.getElementById('ip').onkeyup = function(){
var inputVal = this.value;
if(!(regex.test(inputVal))) this.className='err';
else this.className='noerr';
}
CSS:
.noerr{
color: green;
}
.err{
color: red;
}
Note: HTML5 has inbuilt ways to validate input and also has pseudo-classes like :invalid and :valid to do the same as what the above example does. If you can use HTML5, try this sample. The second input field is done using HTML5 (no JS required).
HTML5:
<input id='iphtml5' pattern='[+-]?\s*\d+(\.\d+)?' type='text' />
CSS:
#iphtml5:valid{
color: green;
}
#iphtml5:invalid{
color: red;
}

Related

How to preview the result of a beforeinput event?

Does the beforeinput event provide a convenient way to preview the result of a proposed modification so that it can be blocked if necessary for validation purposes?
I'm not looking for alternative ways to do input validation; I'm already well-aware of methods involving the keypress and input events, as well as HTML5 validation, etc.. Right now, I'm specifically looking into the beforeinput event to see what it offers.
So far, this is the best I've come up with:
document.getElementById("phone").addEventListener("beforeinput", function(e) {
if(!/^(\d{0,7}|\d{3}-\d{0,4}|)$/.test(e.target.value + (e.data ?? ""))) {
e.preventDefault();
}
return;
});
<input id="phone">
The text field in the above snippet should accept a simple 7-digit phone number with optional dash after the 3rd digit.
Notice that I'm appending the event's data property to the input's current value to create a preview of the modified value. This works fine if you only enter input sequentially. But if, for example, you type in all 7 digits and then arrow back to just after the 3rd and try to insert the dash, you can't do it, because the validation assumes you're at the end where a dash would be invalid. Other problems arise if you try to replace or delete a selection.
An accurate preview will be required to solve these problems. Is there a simple way to get one from the beforeinput event?
You'd have to get the selectionStart and selectionEnd to figure out how many characters were removed / replaced / etc, but yeah, pretty simple:
document.getElementById("phone").addEventListener("beforeinput", function(e) {
const nextVal =
e.target.value.substring(0, e.target.selectionStart) +
(e.data ?? '') +
e.target.value.substring(e.target.selectionEnd)
;
console.log(nextVal)
if(!/^(\d{0,7}|\d{3}-?\d{0,4}|)$/.test(nextVal)) {
e.preventDefault();
}
return;
});
<input id="phone">

How to add auto hyphens between numbers in HTML?

I created input field, when user enter numbers then add auto hyphens.
Format is:
34603-5358722-7
I am using HTML and Javascript
Please share soulution
Thanks
This example shows how to add hyphen - after every 5th letter. You can modify it and add hyphen according to your requirement
function formatData(elem) {
elem.value = elem.value.replace(/(\d{5})(\d{7})/, "$1-$2");
}
<input type='text' onkeyup='formatData(this)'>

How to keep a suffix while masking a input using jQuery

I'm trying to mask a user input with the following mask "########-##.####.7.09.009" using jQuery, so when the user starts typing it would go like this:
1______-__.____.7.09.009 (user typed 1)
12_____-__.____.7.09.009 (user typed 2)
123____-__.____.7.09.009 (user typed 3)
and so on until it reaches the "7.09.009" part.
The user should not be able to edit that part, it is like a fixed placeholder there. I've tried using Jasny's input mask with some success but since numbers are masked with 0's and the fixed suffix has 0's, it allowed the user to type where there are zeroes in the fixed part. I did not find a way to replace the numbers placeholder from 0 to something else, as I imagine that would have solved my problem.
Then I found another jQuery mask plugin that allows me to mask numbers using # but as it also recognizes 0's as a placeholder for numbers, it ended up not working. I also tried creating a custom mask like so:
$("#numero-processo").mask('0000000-00.0000.A.BC.BBC',
{placeholder: "_______-__.____.7.09.009",
'translation': {
A: {pattern: /[7]/},
B: {pattern: /[0]/},
C: {pattern: /[9]/}
}});
This worked to some extent, but when the user reached the fixed suffix part, (he/she) would have to actually type the suffix "7.09.009", and that is the only thing that would be allowed there because of the custom mask. However, I do not want the user to type the suffix, it needs to be fixed there. Does anyone know how to accomplish this? Thank you.
You usually solve this by letting the fixed part outside the input (if the user shouldn't modify it, it's more ergonomic if it's actually not in the alterable part).
<input type="text" />.7.09.009
You can make it nicer with some css around, and you'll have to add it in JS or in the language you use to process the data. So maybe something like that :
<div class="mask_field" addendum=".7.09.009"><input type="text" />.7.09.009</div>
Could be easier to work with.
You could accomplish this using this library
<script src="https://rawgit.com/RobinHerbots/Inputmask/4.x/dist/jquery.inputmask.bundle.js"></script>
Your javascript would be:
<input id="numero-processo" placeholder="_______-__.____.7.09.009" />
<script>
$(document).ready(function(){
$("#numero-processo").inputmask("9999999-99.9999.7.0\\9.00\\9");
});
</script>
Here's a jsfiddle: https://jsfiddle.net/3kyau2p8/
$("#numero-processo").keyup(function(){
var input = $(this).val();
if(input.length == 15) {
input += ".7.09.009";
$(this).val(input);
}
});

How to get value from selected input field (not using id)

I try to do simple code for guessing notes by ear. I have tabs with several empty input fields and you need to put right numbers in these fields according to certain melody (for guitar fretboard) . One button shows first note, another button checks whether you put right or wrong number and depend on it approves or erase your number.
I know how to check every input field using its id's but can i do it such way that when i push 2nd button it get value from selected input and compare it to its placeholder or value attribute?
It is my codepen
https://codepen.io/fukenist/pen/BxJRwW
Script part
function showfirst() {
document.getElementById("fst").value = "12"
}
function show1other() {
var snote = document.getElementById("scnd").value;
if (snote == 9 ){
document.getElementById("scnd").value = "9";
}
else {
document.getElementById("scnd").value = "";
}
}
You can use document.querySelectorAll() to get all your inputs and loop over them.
Sample:
// Get all inputs as an array (actually NodeList, to be precise; but it behaves similar to an array for this use case)
var inputs = document.querySelectorAll('input');
// Function to reveal the first input's value
function showFirst(){
inputs[0].value = inputs[0].dataset.v;
}
// Function to check all values and clear input if wrong
function checkAll(){
inputs.forEach(function(input){
if(input.dataset.v !== input.value){
// Wrong answer, clear input
input.value = '';
}
});
}
<input data-v="12" size="2" value=""/>
<input data-v="9" size="2" value=""/>
<input data-v="8" size="2" value=""/>
<br/>
<button onclick="showFirst()">Show First</button>
<button onclick="checkAll()">Check All</button>
Notes:
I have used data-v to store the correct answer instead of placeholder as that attribute has a semantically different meaning
It may be out of turn but my two cents: Writing out entire songs like this by hand may become tedious. Consider using a JSON string or something similar to map out the tabs and use a templating framework to align them.. Some things you may need to look out for while designing something like this : Alignment of notes (successive notes, simultaneous notes), timing of the song, special moves like slide, hammer on etc.
It may be a better idea to make the Guitar Strings be a background element (either as a background-image or as absolutely positioned overlapping divs) (so You don't have to worry about the lines going out of alignment)
Reference:
HTMLElement.dataset
document.querySelectorAll

masking input text field with asterisk (*) using Jquery or javascript

Masking input text field with asterisk (*) using Jquery or javascript.
Can anybody give the solution for this.
I have searched a lot and not getting any answer.
Even tried javascript,jquery with pure coding asterisk is coming . The problem is: I'm not able to get the proper value.
$(document).ready(function(){
var val1="",val2="",val3,x,x1,i,asc;
$("#psw").keyup(function(){
//val1=val1+String.fromCharCode(e.keyCode);
val1=$("#psw").val().toString();
asc=val1.charCodeAt(val1.length-1);
if((asc>=97 && asc<=122) || (asc>=65 && asc<=90))
{
val2=val2+val1[val1.length-1]; //actual value
}
//setInterval(function(){},700);
//alert(val1);
//val1=val1+String.fromCharCode(e.keyCode);
x=val1.length;
x1="";
for(i=0;i<x;i++)
{
x1=x1+"*";
}
//$("#psw").val("");
$("#psw").val(x1);
});
$("#psw").keydown(function(){
val3="";
for(i=0;i<val2.length-1;i++)
{
val3=val3+val2[i];
}
val2=val3;
});
Final value which user will enter in textbox with id="psw" will be stored in val2 according to this code.But proper value not coming because of keyup and keydown latency problem.
Is there any alternate solution.
You know, input has a password type, just use it, instead of create yours!
<input type="password" />

Categories