Checking for invalid characters from an input with jQuerys - javascript

I have an input box where the a username is input'd but if invalid characters are input'd, I want it to error. The code below is what I'm using; What would i put in the "something" section?
var numbers = new RegExp("SOMETHING");
$(this).removeClass("active");
if(($(this).val() == "") || $(this).val().match(numbers))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}

Here are some patterns I wrote them long years ago:
patt['name'] = /^[a-z ,-]+$/i;
patt['username'] = /^[A-z0-9_-]+$/i;
patt['email'] = /^[a-z0-9]+(?:[\.-]?[a-z0-9]+)*#[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['website'] = /^http(s)?:\/\/(www\.)?[a-z0-9]+([-]?[a-z0-9]+)*[\.-]?[a-z0-9]+([-]?[a-z0-9]+)*([\.-]?[a-z]{2,})*(\.[a-z]{2,5})+$/i;
patt['age'] = /^(?:([1][3-9]|[2-9][0-9]))$/i;
patt['subject'] = /[a-z0-9?!:;'&_\. ,-]+/i;
If you want to use them, you should check this condition:
if(($(this).val() == "") || ! $(this).val().match(patt['name'])){ // in case.
...
}
But if you want to check undesirable characters, it'll be a long pattern for username input.

Try this Regex
[A-Za-z]
This will match only lowercase and uppercase characters

Suggest you read a bit about regexes and experiment with them.
To get simply letters and nothing else, just do:
^[a-zA-Z]+$
That allows 1..n lowercase & uppercase letters to be found between start and end, nothing else. Sushanth's version will match partial pieces of the input, letting the user to use spaces, numbers, etc. elsewhere as long as there's one piece of of the input with a word in it.

This should be a full implementation of what you're trying to do:
var invalid = /[^A-Za-z]+/;
$(this).removeClass("active");
if($(this).val() == "" || invalid.test($(this).val()))
{
$("#firstNameErrorMsg").html("First name can only contain letters. ");
}
else
{
$("#firstNameErrorMsg").html("OK");
}

Sushanth is mostly correct, but you will need to match any number of letters, and it has to be from the start to the end only letters, so you should do something like this
var name = new RegExp('^[A-Za-z]+$');
$(this).removeClass('active');
if($(this).val().match(name)) {
$('#firstNameErrorMsg').html('OK');
} else {
$('#firstNameErrorMsg').html('First name can only contain letters.');
}

If you are looking for validating your users input , to only have letters , i would suggest using the char code, something like this :
add the keypress event on the input tag
for the event args passed, check the character code (Some browsers use keyCode, others use which)
function checkOnKeyDown(event){
if (event.KeyCode >= 65 && event.keyCode <=122)
{
//all ok here -- only upper/lowercase letters accepted
}
else
{
//wrong
}
}
Here is a list with all the keyCode to characters mapping ;) : http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Related

Javascript Regex - replacing characters based on regex rules

I am trying to remove illegal characters from a user input on a browser input field.
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(???, ""))
}
I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.
Thanks for any help you can provide.
Brad
You could try the below code:
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}
Replace is using the following regexp: /[^a-z0-9]/g. This matches all characters that are not lowercase or numeric.
You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/
You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:
var inputs = ['abc123', '46432e66Sc'];
inputs.forEach(i => console.log(i + " => " + i.replace(/^[^a-z]+/, "")
.replace(/[^a-z0-9]+/g, "")));
Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.

Javascript remove all characters by regex rules

Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.

RegEx doesn´t work with Replace JavaScript Method

I need some help with Regular Expression, the problem is that I need apply the regex with Replace method in JavaScript. I saw a few post here in Stackoverflow but any regex doesn't works, I don't why.
I need that the user only can type in the input the following data:
100
100.2
100.23
Note: only number, it could be with one or two decimals maximum. Don't allow another symbols, and of course one comma.
I have been reading about it, and I used a few regex generator to see the match, so I made this one:
/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/
I got a little bit confused at the beginning because I used in the replace method:
elementOne.addEventListener("input", function(event) {
this.value = this.value.replace(/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/, '');
});
And right now I read the process like: if I type a letter from a to z,the method will replace to space ''. but the rest doesn't works in the method but works in the generator for example.
Here is an example, you will see in the first input my regex vs Sven.hig regex:
const elementOne = document.getElementById('elementOne');
const elementTwo = document.getElementById('elementTwo');
elementOne.addEventListener("input", function(event) {
this.value = this.value.replace(/^[a-zA-Z]+(\.[a-zA-Z]{0,2})?$/, '');
});
elementTwo.addEventListener("input", function(event) {
this.value = this.value.replace(/^\d+[,]?\d{0,2}/, '');
});
<p>Element One (My RegEx)</p>
<input id="elementOne" type="text" />
<p>Element Two (Stack RegEx)</p>
<input id="elementTwo" type="text" />
Also as a CodePen
Your regex is to match words not numbers you should replace [a-zA-Z]by [0-9] and the \. by \,
so your regex should look like this /^[0-9]+(\,[0-9]{0,2})?/
alternatively you could shorten the pattern /^\d+[,]?\d{0,2}/gm
here is code snippet to prevent user from entering words or any number that doesn't match the pattern
const elementTwo = document.getElementById('elementTwo');
var flag=false
elementTwo.addEventListener("input", function(event) {
pattern=/^\d+[,]?\d{0,2}$/
if (pattern.test(this.value)){
flag=true
l=this.value
if(flag&&this.value.length>1)
return this.value
else flag=false
}
else if(!pattern.test(this.value)&&flag==true){
return this.value=l
}
else if(!pattern.test(this.value)&&flag==false){
return this.value=""
}
});
<p>Element Two (Stack RegEx)</p>
<input id="elementTwo" type="text" />
It looks like you're confusing a few things:
Replacing invalid characters in a string
Defining a validation pattern
Preventing entry of text
If your goal is to validate that your string has the correct format, you'd define a regular expression like:
const validFormat = /^\d+(,\d{0,2})?$/;
console.log(validFormat.test('99')); // true
console.log(validFormat.test('100,23')); // true
console.log(validFormat.test('X00,2E')); // false
console.log(validFormat.test('%#&SJ&#UJ')); // false
If your goal is to remove invalid characters (non-digits, non commas), you can define a regular expression for those invalid characters, but that's not the same thing as making sure your string now has a valid format. RegExp isn't able to do anything like that:
const invalidChars = /[^\d,]/g;
const sanitized = someString.replace(invalidChars, '');
If you want to prevent typing characters, you're better off adding a keydown event handler to your input and prevent the default behavior for invalid keys.
const myInput = document.querySelector('#some-input');
myInput.addEventListener('keydown', ({ key, preventDefault }) => {
if (key !== ',' && (key < '0' || key > '9')) {
preventDefault();
}
});

Not allow space as a first input character in input field [duplicate]

This question already has answers here:
Not allow space as a first character and allow only letters using jquery
(4 answers)
Closed 4 years ago.
I have a name input filed that takes all the characters including space. I want to use regular expression to not allow first character to be a blank space. User must enter at least one valid character before they are allowed to enter space.
Thank you for you help.
I want to use regular expression to not allow first character to be a
blank space.
Instead of using regex you can just capture keys in the input and prevent space from being inserted when it's the first character entered.
document.getElementById("input").addEventListener('keydown', function (e) {
if (this.value.length === 0 && e.which === 32) e.preventDefault();
});
<input id="input"></input>
You should use trim to validate the extra space and then see if atleast a character is added or not.
let str = " ";
console.log(str);
if(!str.trim()) {
console.log("At least a character required");
} else {
console.log(str);
}
let correctStr = " a ";
if(!correctStr.trim()) {
console.log("At least a character required");
} else {
console.log(correctStr);
}
Do you mean to implement something like this? The first character can never be a space, it has to be some char, after the first char, then it can have infinite number of spaces after it.
const el = document.getElementById("demo");
// A function to encapsulate your logic.
const process = e => {
const v = el.value.toString().replace(/\ /g, '');
// Must have length > 0 before the space bar will do anything.
if (v.length == 0 && e.which == 32) e.preventDefault();
// First char must not be a space.
else if (el.value[0] == ' ') el.value = el.value.replace(/\ /, '');
};
// Do whatever here.
const onChange = () => {
el.onkeydown = process;
el.onkeyup = process;
};
// Lazy on ready..
setTimeout(onChange, 100);
<input id="demo" />

allow space between two word using regular expression

I need to block special character except comma. So I am using code given below. Its is working but it is also removing space between two words. fiddle
var chars =/[(,\/\w)]/i;
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
}
});
In terms of usability, manipulating the user's input as they're typing can be very frustrating. In addition, if the user types fast enough it doesn't work anyway (as mentioned by Daniel Knippers, above)
A better bet would be to validate the user's input and let them know in real-time if the input is invalid.
Try this code:
var regex =/^[\w\s\,]*$/i;
$('input').keyup(function(e) {
var message = regex.test(this.value) ? "" : "Error";
$('#message').html(message);
});
jsFiddle version
as far as i am understood, you wants that space should be allowed in txt box
so,
here is your ANSWER
you need to add space after \w
var chars =/[(,\/\w )]/i;
$('input').keyup(function(e) {
var value = this.value;
var char = value[value.length-1];
if(char !== ' ' || value.length==1 || (value[value.length-2]!==' ' )){
if (!chars.test(char)) {
$(this).val(value.substring(0, value.length-1));
}
}
});
please note that i have added space after \w, so the regexp is var chars =/[(,\/\w )]/i;

Categories

Resources