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>
Related
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)">
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>
I'm trying to check if there's a number in a text input using regular expression. Here's the code:
var regex = /^[0-9]+$/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
It works well, but if I add text, then backspace all the way, I get "bad". How can I make it log "good" when there isn't anything in the text input? I don't want to allow spaces, but I want to allow an empty input.
I tried:
var regex = /\s ^[0-9]+$/;
But then whatever I insert in the input, I always get "bad".
This might fit , either you test for your Exp (^[a-zA-Z0-9]+$) or for an empty string (^$).
var regex = /(^$)|(^[a-zA-Z0-9]+$)/;
if (myInput.val().match(regex)) {
console.log("number");
} else {
console.log("bad");
}
try this (* in place of +)
var regex = /^[0-9]*$/;
if (myInput.val().test(regex)) {
console.log("number");
} else {
console.log("bad");
}
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>
I am having a problem to get the simple reges for alphanumeric chars only work in javascript :
var validateCustomArea = function () {
cString = customArea.val();
var patt=/[0-9a-zA-Z]/;
if(patt.test(cString)){
console.log("valid");
}else{
console.log("invalid");
}
}
I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string
This regex:
/[0-9a-zA-Z]/
will match any string that contains at least one alphanumeric character. I think you're looking for this:
/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */
Or possibly this:
var string = $.trim(customArea.val());
var patt = /[^0-9a-z]/i;
if(patt.test(string))
console.log('invalid');
else
console.log('valid');
Your function only checks one character (/[0-9a-zA-Z]/ means one character within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.
I fixed it this way
var validateCustomArea = function () {
cString = customArea.val();
console.log(cString)
var patt=/[^0-9a-zA-Z]/
if(!cString.match(patt)){
console.log("valid");
}else{
console.log("invalid");
}
}
I needed to negate the regex