Copy/paste validation on input field and restrict character - javascript

I am working on validation of an input control when the user copy paste some value in it
On pasting to this input I want to strip out as below:
Input can start with underscore or an alphabet
Input cannot start with number
Input cannot have any spl character except underscore
Input cannot have spaces
This is allowed:
abc
abc_123
_123bcd
_123_bcd
This is not:
123abc
123_acd
abc s22
I tried with the below code:
#HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.stripInput(event);
}
stripInput(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]+/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100);
}
But with above code its not fully working, it doesnt allows:
abc_123
_123_ams
Any inputs please

You have made a simple over sight with regards to your initial regex. You did not add a start of string check (which is needed to remove numbers and extra special characters at the start of the string). You will also need another query if you want to remove other special characters from within the string as well
if you change your last block of code to -
#HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) {
this.stripInput(event);
}
stripInput(event) {
setTimeout(() => {
this.el.nativeElement.value = this.el.nativeElement.value.replace(/^[^A-Za-z_]+/g, '').replace(/[^0-9A-Za-z_]+/g, '').replace(/\s/g, '');
event.preventDefault();
}, 100);
}
It should work as expected (Note the extra ^ at the start of the regex and the added _ to your initial regex as well as the extra following regex).
What this does pin the search to the start of the string instead of allowing it to act on all parts of the string. It works on your abc_123 _123_ams input and it also strips the extra space in the middle of it as intended. (it makes it abc_123_123_ams)

Related

use replace to remove chars not existing in a regex match

I'am trying to allow following pattern for a single html input box with javascript regex
-int (aka any minus number so long it not followed by a zero and is in the first position)
0 (a single zero is allowed)
int (is allowed)
I use this function the remove anything that doesn't match it
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.
Other examples is:
/[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
(/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
[^1-9-]?[^0-9]* Allow all...
I think I'am missing something.. Any suggestions would be most appreciated..
You may try this regex
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3 after input
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
In short:
generally only -, 0-9 are allowed.
if you type a 0 first, nothing will be allowed after.
if you type a 1-9 first, only numbers are allowed after.
if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
I changed your regexp and made it a bit more modular and it worked fine.
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
Orginal RegEXP in Stackoverflow

AngularJS filter to remove a certain regular expression

I am attempting to make an angularJS filter which will remove timestamps that look like this: (##:##:##) or ##:##:##.
This is a filter to remove all letters:
.filter('noLetter', function() {
//this filter removes all letters
return function removeLetters(string){
return string.replace(/[^0-9]+/g, " ");
}
})
This is my attempt to make a filter that removes the time stamps, however it is not working, help is much appreciated.
.filter('noStamps', function () {
return function removeStamps(item) {
return item.replace(/^\([0-9][0-9]:[0-9][0-9]:[0-9][0-9]\)$/i, "");
}
})
My goal is for it to delete the timestamps it finds and leave nothing in their place.
edit based on question in comments:
The time stamps are in the text so it would say "this is an example 21:20:19 of what I am 21:20:20 trying to do 21:20:22"
I would want this to be converted into "this is an example of what I am trying to do" by the filter.
You may use
/\s*\(?\b\d{2}:\d{2}:\d{2}\b\)?/g
See regex demo
Thre main points:
The ^(start of string) and $(end of string) anchors should be removed so that the expression becomes unanchored, and can match input text partially.
Global flag to match all occurrences
Limiting quantifier {2} to shorten the regex (and the use of a shorthand class \d helps shorten it, too)
\)? and \(? are used with ?quantifier to match 1 or 0 occurrences of the round brackets.
\s* in the beginning "trims" the result (as the leading whitespace is matched).
JS snippet:
var str = 'this is an example (21:20:19) of what I am 21:20:20 trying to do 21:20:22';
var result = str.replace(/\s*\(?\b\d{2}:\d{2}:\d{2}\b\)?/g, '');
document.getElementById("r").innerHTML = result;
<div id="r"/>

Regex is confusing me and why won't it parse properly?

Sorry about the confusing title. I'm new to Regex and JS/JQ in general. However, I'm trying to parse this. Basically, I want it to add the key pressed to the HTML if and ONLY if the keys 0-9 and the keys +, -, /, and * are pressed. Any help would be much appreciated. Here is my code:
function charCode(code) {
return String.fromCharCode(code);
}
function escapeChars(esc) {
return esc.replace(/[0-9\+-\*\/]*$/, "");
}
$('#tb').html("0");
$(document).on("keydown", function(event) {
var div = $('#tb');
var which = event.which;
which = charCode(which);
which = escapeChars(which);
else if (div.html() == "0") {
//alert("Div is equal to 0."); --Debug
div.html(which);
} else {
//alert("Div is equal to " + div.html()); --Debug
div.html(div.html() + which);
}
});
Currently, it doesn't allow anything through.
There's a couple problems with your regular expression.
You want to replace characters that do not match your list. To do that, you start your character class ([]) with a ^.
You don't need to escape + or * in the regular expression. You do need to move the - to the beginning or end though.
You don't need the * or the $ after the character class. Dropping those, you'll replace any character that doesn't match, no matter where it occurs in the string.
In case your string contains more than one character (may not apply here), adding a g flag to the end will allow you to replace all characters that do not match.
That results in a regular expression that looks like this:
/[^0-9+*\/-]/g
This fiddle shows the above regular expression working: http://jsfiddle.net/WyttT/
Updated
Another problem you're encountering is caused by checking keycodes from a keydown event. The keycodes on keydown do not match to actual ascii character codes, so non-alphanumeric keys are getting converted into weird characters. If you change your even handler to respond tokeypress instead, you'll get better results.
I don't think you want a regex for this. I think charAt() will do what you want far more simply.
You have a character. You have a list of characters which either match it or don't. charAt() does that simply and efficiently.
Now that jcsanyi has helped you with the regex, here is a simplification of your JS code. Codepen
You will want to use keypress instead of keydown/keyup, otherwise your numpad will return the wrong keys, and anything requiring a shift (shift+8 = * for instance) won't work. You can also use RegExp.test(String) to check if the character is valid, and div.append(char) in place of div.html(div.html + char).
var div = $('#tb');
$(document).on("keypress", function(event) {
var char = String.fromCharCode(event.which);
if (/[0-9+*\/-]/.test(char) === true) {
div.append(char);
}
});

jQuery input filter for textarea

I adapted this solution into my script. The idea is to prevent the user from typing unauthorized characters (of course there is also a filter on the back end).
$('#someinput').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
console.log(str);
return '';
}))
})
It works nice, but I also need the users to be able to type specific allowed characters like: .,!?ñáéíóú - I mean, the basic a-zA-Z0-9 plus some basic chars and the whole bunch of special language characters.
What actually needs to be left out are: ##$%^&*()=_+"':;/<>\|{}[]
Any ideas? Thanks!
Solution thanks to Michael
//query
$('#someinput').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
setTimeout(function() {
$('#someinput').val($('#someinput').val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
$('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
},100);
});
Invert your regular expression to only replace the specific characters you want omitted:
$th.val( $th.val().replace(/\s?[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars
Note, a few of them need to be escaped with a backslash inside a [] character class: \\\[\]\^\/
If I'm understanding what you are wanting to do, can't you just add those unwanted characters to your regex instead of doing the [^a-zA-Z0-9]?
Replace that with [##\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]] (notice the escaping)

Javascript Regular Expressions - Required field validation

How do I check if a field (textbox) is empty or filled only with white spaces (spaces/enters/tabs etc.), using javascript RegExp?
if (myField.value.match(/\S/)) {
// field is not empty
}
// or
if (/\S/.test(myField.value)) {
// field is not empty
}
Explanation, since other people seem to have some crazy different ideas:
\s will match a space, tab or new line.
\S will match anything but a space, tab or new line.
If your string has a single character which is not a space, tab or new line, then it's not empty.
Therefore you just need to search for one character: \S
/^\s*$/.test(string)
Could be used like so:
var empty_string = /^\s*$/; //create RegExp object for re-use
if (empty_string.test(myFormField.value))
{
alert("Please be a bit more elaborate!");
}
By testing for
/\s/ or /\S/ you will only be testing for one character . So , it will be better to test instead for :
/^\s+$/ or /^\S+$/
EDIT: please note that or is not part of the code .
EDIT2:
The test for matching :
if(string.match(/^\s+$/)) {
alert("string is empty!");
}
And the test for non-matching :
if(!string.match(/^\S+$/)) {
alert("string is empty!");
}
You could use either of these to same result .

Categories

Resources