Block user from input with regex - javascript

I have a function which checks an input box with an regex string for max. 3 words and two spaces.
$('input.words_input__input_field').on("keyup", function(e) {
if (e.keyCode == 13) {
send_message();
}
var re = /^((([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)){3}$/g;
var str = $('input.words_input__input_field').val();
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
send_text = str;
// View your result using the m-variable.
// eg m[0] etc.
}
console.log(m);
});
When the Regex applies on the input value the send_text will not be edited anymore. But I want to prevent the user from typing anymore into the input box.
Is there any way to create a block for the input so that the user cannot type in more than as "allowed" by the regex?
EDIT: I have some problems with this regex, so it works too perfect it should only prevent the user from typing in after three words and two spaces are in the input field. I have a code like this:
var test = /^((([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)){3}$/g;
if (test.test($(this).val())) {
$(".input").val($(".input").val().replace(/\s/g, ""));
}
But it "kills" all whitespaces. And I only want to delete the whitespaces at the end. Any ideas?

Set the input to disabled with
$('input.words_input__input_field').prop('disabled', true);
Or store the .val() in a variable or a data object as long as it's valid and regenerate it from there if the regex is not met anymore.
EDIT:
The code below will let the user type 3 words, separated by commas. If anything is added that violates the regex, the input will be reset to the last value.
var p;
var f;
$(".inp").on('keyup',function(e){
var k = e.which;
var i = $(".inp").val();
if(k != 8 && k != 46){ // allow backspace and delete
if(i.search(/^[A-Za-z]+ [A-Za-z]+ [A-Za-z]+$/) >= 0){
f = true;
p = i;
}
else{
if(f){
$(".inp").val(p);
}
}
}
});
<input type="text" class="inp">
Fiddle

Related

How to replace new line character with comma in angular

I have one textarea field in which the user can enter input in a new line as well as comma-separated values. so when I m sending values in API /n is appended in case of the new line and same /n is visible on detail page which I don't want. below is the example of user input.
Ex-1
ABC
red
test,blue
Ex-2
abc,blue,
green,red
test
I want each time to check for new line break and comma, my mean is to say
if user enter values in new line then replace newline character with a comma and if a comma is already appended
then keep it as it is.
Expected output
Ex-1
ABC,red,test,blue
Ex-2
abc,blue,green,red,test
Below is my code
createData(data) {
const Obj = {};
if (data.enum && data.value_type === 'Enum') {
Obj['values'] = data.enum.split(',');
}
console.log(Obj,"constraint");
return Obj;
}
You need first split the string with a newline character, Remove any empty string from the array once it's done joined it with ,. Also, we need to take care of some double comma as string contain a comma.
var str = `ABC
red
test,blue`;
var str2 = `abc,blue,
green,red
test`;
formateString(str);
formateString(str2);
function formateString(str) {
var strArray = str.split("\n");
strArray = strArray.filter((item) => {
return item !== '';
});
console.log(strArray.join(",").split(",,").join(","));
}
Using regex split()
Regex Demo
const str1 = `ABC
red
test,blue`;
const str2 = `abc,blue,
green,red
test`;
console.log(str1.split(/[,\n]+\s+/g).join(','))
console.log(str2.split(/[,\n]+\s+/g).join(','))
Another approach is to intercept input every time user enters character. With this method you avoid parsing whole text over and over again with every keystroke (including redundant ones).
Following is a simple piece of code that substitutes newlines and spaces with commas on the fly. Assuming you have a textarea with id textArea somewhere in your HTML.
const textArea = document.getElementById('textArea');
const parseText = function parseText(e) {
if (e.keyCode === 13 || e.keyCode === 32) {
e && e.preventDefault();
let text = textArea.value;
let curStart = textArea.selectionStart;
let curEnd = textArea.selectionEnd;
if (curStart == text.length && curEnd == text.length && !text.endsWith(',')) {
text += ',';
textArea.value = text;
}
}
}
textArea.addEventListener('keydown', parseText);
Regards

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" />

Replace content present in the nested brackets

Input = ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))
Expected Output = ABCDEF,GHIJKLMN,OPQRSTUVW
Tried so far
Output = Input.replace(/ *\([^)]*\)*/g, "");
Using a regex here probably won't work, or scale, because you expect nested parentheses in your input string. Regex works well when there is a known and fixed structure to the input. Instead, I would recommend that you approach this using a parser. In the code below, I iterate over the input string, one character at at time, and I use a counter to keep track of how many open parentheses there are. If we are inside a parenthesis term, then we don't record those characters. I also have one simple replacement at the end to remove whitespace, which is an additional step which your output implies, but you never explicitly mentioned.
var pCount = 0;
var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = "";
for (var i=0; i < Input.length; i++) {
if (Input[i] === '(') {
pCount++;
}
else if (Input[i] === ')') {
pCount--;
}
else if (pCount == 0) {
Output += Input[i];
}
}
Output = Output.replace(/ /g,'');
console.log(Output);
If you need to remove nested parentheses, you may use a trick from Remove Nested Patterns with One Line of JavaScript.
var Input = "ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))";
var Output = Input;
while (Output != (Output = Output.replace(/\s*\([^()]*\)/g, "")));
console.log(Output);
Or, you could use a recursive function:
function remove_nested_parens(s) {
let new_s = s.replace(/\s*\([^()]*\)/g, "");
return new_s == s ? s : remove_nested_parens(new_s);
}
console.log(remove_nested_parens("ABCDEF ((3) abcdef),GHIJKLMN ((4)(5) Value),OPQRSTUVW((4(5)) Value (3))"));
Here, \s*\([^()]*\) matches 0+ whitespaces, (, 0+ chars other than ( and ) and then a ), and the replace operation is repeated until the string does not change.

Restrict a text box to allow special characters at starting

I need to validate a text box which i am using for search the content which comes from database.Need to restrict special characters at starting but allow after a word.And space also.
Ex: Must allow
java/j2ee
java&servlets
But Not
#java
$java
(space)java
$("#keyvalue").keypress(function (e) {
var regex = new RegExp("^[a-z0-9][a-z0-9_ .-]*$");
var regex1 =new RegExp("[,%_$]");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)){
$("#errormess").html("Please select valid input").show();
}
if(regex1.test(key)) {
e.preventDefault();
} else {
$("#errormess").html("");
}
});
Try something like this
function isValid(){
return !/[#$\s\/&]/g.test(yourString.indexOf(0));
// Returns true if special char not exists at first position
}
You can add more special characters in [#$\s\/&]
Check this snippet
var textbox = document.getElementById('textbox');
var pattern = /^([a-zA-Z0-9]+)([a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?\s]+)$/;
if(!pattern.test(textbox.value)){
console.log('Not allowed!');
}
or this one, having less complex regex
var textbox = document.getElementById('textbox');
var pattern = /^([a-zA-Z0-9].*)$/;
if(!pattern.test(textbox.value)){
console.log('Not allowed!');
}

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