regex: alphanumeric spaces and dash on keyup [duplicate] - javascript

This question already has answers here:
How to prevent non-alphanumeric input in javascript?
(5 answers)
Closed 9 years ago.
I've seen plenty of posts close to what I'm looking for, but I'm still getting errors and was hoping for some regex help. I have a form field that needs to allow alphanumeric, spaces, and dashes. Ideally the spaces and dashes would not be consecutive.
I want this to fire on keyup so that the user doesn't have the option to type these forbidden characters.
Here's what I have so far, but I'm throwing bad escaping errors and this code does not work in firefox. Thanks for your help!
$('#your_name').keypress(function (e) {
var allowedChars = new RegExp("^[a-zA-Z0-9\-\ ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
}).keyup(function() {
var forbiddenChars = new RegExp("[^a-zA-Z0-9\-\ ]", 'g');
if (forbiddenChars.test($(this).val())) {
$(this).val($(this).val().replace(forbiddenChars, ''));
}
});

Try this:
$('#your_name').keyup(function (e) {
var allowedChars = /^[a-z\d -]+$/i;
var str = String.fromCharCode(e.charCode || e.which);
var forbiddenChars = /[^a-z\d -]/gi;
if (forbiddenChars.test(this.value)) {
this.value = this.value.replace(forbiddenChars, '');
}
if (allowedChars.test(str)) {
return true;
}
e.preventDefault();
return false;
});

Related

Regex Pattern working in regex tester but not in actual code [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 6 years ago.
The following regex check is not working in the code. But if i use this pattern at regex101.com it works perfectly
var pattern = "^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$";
var value = "test#user.com";
var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
alert("Failed");
} else {
alert("passed");
}
Could you please help me why this is happening here. By the way if i make some modifications like given below, it works. But i want it to work with (new RegExp(pattern))
var pattern = /^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$/;
var value = "test#user.com";
if (!pattern.test(value)) {
alert("Failed");
} else {
alert("passed");
}
Just remove the double quotes and put your Regex simply in forward slashes.
var pattern = /^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$/;
var value = "test#user.com";
var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
alert("Failed");
} else {
alert("passed");
}
It's because, if you're putting double quotes, then you need to escape your regular expression
However, you can simply put your regular expression as it is when placing it between forward slashes.
You need to escape those backslashes (\).
var pattern = "^([a-zA-Z0-9]([-\\.\\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\\w]*[a-zA-Z0-9]\\.)+[a-zA-Z]{2,9})$";
var value = "test#user.com";
var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
console.log("Failed");
} else {
console.log("passed");
}

Checking regex expression on keypress

I would like to create my own plugin (without use any external libraries - it's for learning purpose) to validate text typed by user dynamically in regex test function.
In example I have regex pattern:
^.{2}$
And javascript function
$('#textbox').bind("keypress", function (event) {
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Now, I want to type two dots into textbox, but after first keypress is fired, one dot doesn't match to the pattern and nothing happens because event is prevented.
My question: Is it possible to check if currently typed text matches with regex pattern?
Your regex only accept two dots (..), but you're testing a single character!
var regex = new RegExp("^.{2}$");
$('#textbox').bind("keypress", function (event) {
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
Wanna check current typed text when users finished typing? .. Look HERE
var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/;
var alphanumeric = /[ A-Za-z0-9]/;
function validateKeypress(validChars) {
var keyChar = String.fromCharCode(event.which || event.keyCode);
return validChars.test(keyChar) ? keyChar : false;
}
The HTML will have to change to onkeypress="validateKeypress(alpha);"
You can try keydown as it will trigger as soon as you press a key and before character is displayed in textbox. So if it doesnot match with the pattern you can return out.
$('#textbox').bind("keyup", function (event) {
var user_input = getElementById ("your_input_id_here");
if (!regex.test(user_input)) {
return false;
}
});
So, essentially you should use onkeyup instead and you should check the whole user input, not just the last key
var in_put = document.getElementById("in_put"),
key = null;
in_put.addEventListener("keydown", match_input);
function match_input(e){
console.log("Key: "+e.key);
key = e.key;
console.log("Match: "+key.match(/a/i));//return array of match
if(key.match(/a/i)){
//code on succession.
}else{
//code on failure.
}
}
Note: Change /a/i with your /pattern/ig. It only check for input is
a/A.

Javascript regex allow only specific characters

I am using following code to allow only a-z, A-z, space, newline, tab.
But it doesn't allow tab key.
Here is my javascript code.
// Filter invalid characters in title
$('#p_title').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9 \b\n\r\f\t\v]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
You need to double escape all escape sequences for constructing RegExp object. However better to just use regex literal in your case:
var regex = /^[a-zA-Z0-9 \b\n\r\f\t\v]+$/;
Full code:
$('#p_title').keypress(function (e) {
var regex = /^[a-zA-Z0-9 \b\n\r\f\t\v]+$/;
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
Try use .on instead .keypress:
http://jsfiddle.net/z9wvfj1e/1/
// Filter invalid characters in title
$('#p_title').on('keydown', function (e) {
if (e.keyCode >=37 && e.keyCode <=40) return true;
var regex = new RegExp("^[a-zA-Z0-9 \b\n\r\f\t\v]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
console.log(e);
return true;
}
e.preventDefault();
return false;
});
Something like this sounds like all you need:
$('#p_title').keypress(function (e) {
return /[a-z]|\s|\r?\n|\t/i.test(String.fromCharCode(e.which));
});
I am doing a case-insensitive check for whether the character entered is a letter OR a space OR a newline OR a tab.
Furthermore, you don't need to check for e.charCode with jQuery because:
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
https://api.jquery.com/event.which/

.replace doesn't work [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I wrote this code to replace some chars in a string:
$(".rtl:not(.num)").keypress(function(e)
{ var key = (e.keyCode || e.which);
var vlu = $(this).val();
var charTyped = String.fromCharCode(key);
if (charTyped=='ك')
{ vlu.replace(/ك/g,'ک');
alert("keh"); }
if (charTyped=='ي')
{ vlu.replace(/ي/g,'ی');
alert("yeh"); }
alert(vlu);
});
After the code executes, vlu has not changed. What is wrong?
Replace does not change the original string, it returns a new string.
MDN String replace()
var str = "abc123";
var updated = str.replace("123","");
console.log("str: ", str);
console.log("updated: ", updated);

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!');
}

Categories

Resources