Javascript regex allow only specific characters - javascript

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/

Related

Regex to block all special characters

I'm trying to write a regex for an name field and block all special characters
JS Fiddle: https://jsfiddle.net/69mqhzq6/
However, my code seems to ignore it. Could someone tell what I'm doing wrong?
$('input').on('keypress', function (e) {
var blockSpecialRegex = new RegExp("~`!##$%^&()_={}\[\]\:;,.\/<>/-+/?");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
console.log(key)
if(blockSpecialRegex.test(key) || $.isNumeric(key)){
e.preventDefault();
return false;
}
});
You just enumerated the special chars without creating a character class defined with the help of [...].
I suggest using a regex literal with a character class matching any of the symbols defined in it:
var blockSpecialRegex = /[~`!##$%^&()_={}[\]:;,.<>+\/?-]/;
Note that the - should be at the start/end of the character class to denote a literal - symbol. The ] inside must be escaped, but [ does not have to be escaped. / must be escaped because it is a regex delimiter symbol.
JS code:
$('input').on('keypress', function (e) {
var blockSpecialRegex = /[~`!##$%^&()_={}[\]:;,.<>+\/?-]/;
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
console.log(key)
if(blockSpecialRegex.test(key) || $.isNumeric(key)){
e.preventDefault();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text">
Why not use a regex to allow only alphabets,numbers and spaces(if required)
^[A-Za-z0-9 ]*$
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.
So you need to do this:
var blockSpecialRegex = new RegExp("[~`!##$%^&()_={}\\[\\]\\:;,\\.\\/<>\\\\*\\-+\\?]");
See RegExp - Javascript

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.

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

Jquery Validation: allow only alphabets and spaces

My validation accepts only alphabets. I want allow spaces as well.
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z]+$/);
});
What change needs to be done here?
Instead of the below regex:
/^[a-zA-Z]+$/
Use this:
/^[a-zA-Z\s]+$/
This will also take the space.
Just leave a space or use \s in your regex:
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z\s]+$/);
// -- or leave a space here ^^
});
jQuery.validator.addMethod("lettersonlys", function(value, element) {
return this.optional(element) || /^[a-zA-Z ]*$/.test(value);
}, "Letters only please");
Use pattern: /^[a-zA-Z ]*$/
Your validation is proper. You just need to change regex /^[a-zA-Z ]*$/
$.validator.addMethod("alpha", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z ]*$/);
});
**
I have tried above but space was an issue in above given regex
/^[a-zA-Z\s]+$/ and /^[a-zA-Z]+$/. The Below worked for me:
**
$('.name-val').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z ]+$");
var strigChar = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(strigChar)) {
return true;
}
return false
});
Please use these pattern for validation.
var pattern = /^[a-zA-Z ]+$/;
if(!pattern.test(name) && name !=''){
return false;
}

regex: alphanumeric spaces and dash on keyup [duplicate]

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

Categories

Resources