Validate input time (in minutes) - javascript

I need to put in a field the input of time in minutes so I create this regular expression in javascript:
var pattern = new RegExp('[1-9]+[0-9]*') //the 0 is not a correct value for input
var example = "44445/";
if (pattern.test(example)) {
}
My problem is that the program enters in the if also in the string there is the "/" value. How is it possible?Anyone can example me?

You missed the start and end anchors. If you don't use anchors, then the regular expression will only check if the string contains the numbers.
Using anchors will make sure that the string contain only the specified characters.
var regex = /^[1-9]+[0-9]*$/;
Your regex can also be written as
var regex = /^[1-9]\d*$/;
function testValue(value) {
return /^[1-9]\d*$/.test(value);
}
<input type="text" onblur="document.getElementById('i1').value = testValue(this.value)">
<input type="text" readonly id="i1">

Related

how to prevent adding scripts in input fields

I need to prevent adding scripts inside input fields.is there any way to prevent adding javascript codes in text fields/text areas?
function filter($event) {
var regex = /[^a-zA-Z0-9_]/;
let match = regex.exec($event.target.value);
console.log(match);
if (match) {
$event.preventDefault();
} else {
return true;
}
}
You can sanitize the input by defining the blacklist regex which contains the patterns not allowed by the input and then replaced the part of input string with empty string if matched with the blacklist regex.
For now I just added a simple blackList regex (You can modify it as per your requirement) which will replace all the text comes between < and >. For Ex: If user enter <script>Hello</script> (This whole input text will get replaced with the empty string on keyup event.
const blackList = /<+>/ig
function sanitizeInput() {
const inputStr = document.getElementById('inputStr').value;
console.log('inputStr', inputStr)
document.getElementById('result').innerHTML = inputStr?.replace(blackList, '')
}
<input type="text" id="inputStr" onkeyup="sanitizeInput()"/>
<div id="result"></div>

How to prevent user from copy-pasting text with invalid characters into input text field immediately on copy-paste action?

I have read few answers online and here on stack overflow but I am not finding a solution.
I am trying to prevent user from copy-pasting invalid characters (anything other than a-z A-Z characters) into my input field. I dont want to do this on submit but on copy-paste event.
If I copy paste text that has all invalid characters (like '1234'), my if block will get executed (regex test fails) and that works fine.
However, it does not work if my copied text contains mix of valid or invalid characters (like '12abc' or 'abc12').
How do I prevent user from copy-pasting text with invalid characters into my input text?
I am calling my javascript function on input text element like this:
function validatePaste(e) {
var regex = /[a-z]/gi;
var copiedText = e.clipboardData.getData('text')
console.log(copiedText,regex.test(copiedText) )
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes only if copiedText has all invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
References:
Character classes ([...]), Anchors (^ and $), Repetition (+, *)
The / are just delimiters, it denotes the start and the end of the regex. One use of this is now you can use modifiers on it.
function validatePaste(e) {
var regex = /^[a-zA-Z]*$/;
var copiedText = e.clipboardData.getData('text')
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes only if copiedText has all invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">
You only test there is one char there
Here is a better regex - also we do not need to assign it every time
const regex = /^[a-z]+$/gi; // gi makes A-Z irrelevant
function validatePaste(e) {
const copiedText = e.clipboardData.getData('text')
console.log(copiedText, regex.test(copiedText))
if (!regex.test(copiedText)) {
e.preventDefault(); //this line executes if copiedText has any invalid characters
return false;
}
}
<input type="text" onpaste="validatePaste(event)">

Remove special characters from input field

I've been searching everywhere but have been unable to find exactly what I am looking for.
I have an html form that is filled out with Mac addresses from our inventory so the strings inputted into the input field will look like:
A1:A2:A3:A4:A5:A6
I'm trying to write a script to remove the : character plus any spaces anywhere. That way when it is entered the output will be:
A1A2A3A4A5A6
This is what I have so far:
<input type="text" id="macaddress" onChange="removeChar();WriteLog();" />
Then in my script I have:
function removeChar() {
var a = document.getElementById("macaddress").value;
a = a.replace(/: /g, '');
document.getElementById.innerHTML = a;
}
I don't get any JavaScript errors with this but nothing happens.
I also have another script that pulls the value of the field into a work log which is the other function WriteLog().
Essentially I want to remove the : then have the new value pulled into the log by the second function.
If you want to keep only numbers and letts you can use this
a.replace(/[^a-zA-Z0-9]/g, '');
which basically replaces everything that isn't a-z or A-Z or 0-9 with an empty string.
A great tool for explaining regex and testing it is Regex101
And this line document.getElementById.innerHTML = a; should be fixed as well, you probably meant something like document.getElementById('some-elements-id').innerHTML = a;
Question spec says you want to remove : and : with space. Make the space in the regex optional:
a = a.replace(/:( )?/g, '');
But you also need to account for preceeding spaces:
a = a.replace(/( )?:( )?/g, '');
I would also trim the initial string (Just good practice)
a = a.trim().replace(/( )?:( )?/g, '');
Finally, I am not sure what this line does:
document.getElementById.innerHTML = a;, but that line will throw an error. Remove it.
to remove colons and spaces from string simply use
str = str.replace(/[:\s]/g, '');
HTML
<input type="text" id="macaddress"/>
<button onclick="removeChar()">Click me!</button>
JS
function removeChar() {
var a = document.getElementById("macaddress").value.trim();
a = a.split('');
a.forEach(function (character, index) {
if (character === ':') {
a.splice(index, 1);
}
});
a = a.join('');
document.getElementById("macaddress").value = a;
}
Your Regex searches for "colon immediately followed by space".
If you add a pipe in between them: /:| /, then it will search for all colons and/or spaces, in any order.
Demo:
function removeChar() {
var a = document.getElementById("macaddress").value;
a = a.replace(/:| /g, '');
document.getElementById("result").innerHTML = a;
}
<input type="text" id="macaddress" onChange="removeChar();" />
<div id="result"></div>

Extract value from string in JavaScript

I'm quite new to JavaScript, so the code below can be pretty bad. I'm just trying to extract a value from a string. I know parseFloat() would probably not be the solution, but is there any function that would allow for that?
p id="1" would contain some random text and end with a value.
Here below my example:
<div id="abc">
<p id="1">abc 0.99</p>
<p id="2">-</p>
<button onclick="GetValue()">Extract value</button>
</div>
<script>
function GetValue() {
var Value = parseFloat(document.getElementById("1").innerHTML);
document.getElementById("2").innerHTML = Value;
}
</script>
Any suggestion is much appreciated!
The suggestion from this other thread JavaScript get number from string worked, thanks for pointing that out!
Updated code:
<div id="abc">
<p id="1">abc 0.99</p>
<p id="2">-</p>
<button onclick="GetValue()">Extract value</button>
</div>
<script>
function GetValue() {
var String = document.getElementById("1").innerHTML;
var Value = String.replace( /^\D+/g, '');
document.getElementById("2").innerHTML = Value;
/*
Solution 2> var Value = String.replace(/^.*?(-?([0-9]+|[0-9]*[.][0-9]+))[ \t]*$/gi,'$1');
Solution 3> var Value = String.match(/\d+(\.\d+)?/)[0];
*/
}
</script>
You can use following regex:
var str = "abc 0.99";
let number=str.match(/\d+(\.\d+)?/)[0];
alert(number);
Regex Explanation
0-9 : Matches any number
. : Matches . literal
+ : Matches previous group one or more time
When the structure of your string is always like "textspacenumber" where number is always at the end, you could just split the string and use the last item:
const str = "abc 0.99";
const tokens = str.split( ' ' );
const number = parseFloat( tokens[ tokens.length - 1 ] );
console.log( number );
This is way simpler than using RegEx (which is fine too, but slower)
parseFloat is fine, if you really need the numerical value. The "some random text and end with a value" part can be a bit tricker, depending on what that text can be. (for example can it contain other numbers?)
Here's a way to do it with regular expressions:
var s = document.getElementById('1').innerHTML;
s = s.replace(/^.*?(-?([0-9]+|[0-9]*[.][0-9]+))[ \t]*$/gi,'$1');
var x = parseFloat(s);
document.getElementById('2').innerHTML = x;
Explanation of the 2nd line: this is a regular expression that extracts a numerical part from the end of a string. A 'numerical part' here may start with a minus sign (for negative numbers), and then either just a bunch of digits (for integer values), or zero or more digits followed by a decimal point followed by one or more decimals. I've added [ \t]* to also allow for some optional whitespace at the end.
This can look pretty crazy if you're not familiar with regular expressions.
By the way, since you're only putting the result back into your HTML content, there is actually no need for parseFloat. You can just put the resulting s (which is still a string but only the number, with the content before number stripped away) straight back into the HTML.
If you are doing actual calculations with the number, then yes, use parseFloat(s).
Try this:
function GetValue() {
var myValue = document.getElementById("1").textContent;
document.getElementById("2").innerHTML = myValue;
}
Note: You were trying to assign value to a system variable - Value.
Code runing: https://jsfiddle.net/2ohf65hc/

Javascript Regular Expression to add dash after every 3rd and 4th characters

The following regex:
x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, "-");
adds dash after each 3rd character so entered 123456789 turns into 123-456-789.
Im trying to use this regex to format phone number. The problem arises on the 10th character. So entered 1234567890 turns into 1-234-567-890.
How would I modify the above regex to turn strings that have 10 digits into 123-456-7890. I use this regex because this happens as user is typing in uses keyup event.
If you know easier or better way of doing this please help me out, dashes has to be added while user is typing in. No other characters allowed.
Notes:
Cant use Jquery Masked input plugin (because if editing the middle character it's focus gets messed up)
How about
> "12345678".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-78"
> "123456789".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-789"
> "1234567890".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-7890"
If you ALREADY have the complete number or string
var x = "329193914";
console.log(x.replace(/(\d{3})(\d{3})(\d{3})/, "$1-$2-$3"));
If you WANT AS someone is typing...
$('#locAcct').keyup(function () {
var foo = $(this).val().split("-").join(""); // remove hyphens
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,3}', 'g')).join("-");
}
$(this).val(foo);
});
Do you need to use regular expressions for everything or would maybe something like this also help you out?
function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/[^\d]/g,"");
while (text.length >= 6) {
result.push(text.substring(0, 3));
text = text.substring(3);
}
if(text.length > 0) result.push(text);
return result.join("-");
}
You could use this function everytime the text in your inputfield changes. It will produce the following results:
"12345678" -> "123-45678"
"123d456789" -> "123-456-789"
"123-4567-89" -> "123-456-789"
I believe the simplest way would be to add dash after every n digits would be like
var a = $('#result');
var x = "<p>asiija kasdjflaksd jflka asdkhflakjshdfk jasd flaksjdhfklasd f</p><p>12345678912345678912345678912312344545545456789</p>"
a.html(x.replace(/(\d{15})/g, "$1-"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
Most easiest way is the following using simple javascript onkey and function... it will put dash hyphen after every 3 characters you input / type.
<input type="text" class="form-control" name="sector" id="sector" onkeyup="addDash(this)" required>
add the following script
<script>
function addDash (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.match(/.{1,3}/g).join('-');
document.getElementById(element.id).value = finalVal;
}
</script>

Categories