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.
Related
Not a lot of experience in RegEx stuff.
I have the following in java script which works perfectly fine.
The following pattern is used allow only alpha numeric
var valid = /^[A-Za-z0-9]+$/.test("a"); // returns true
var valid = /^[A-Za-z0-9]+$/.test("#"); // returns false
I am using the pattern part "^[A-Za-z0-9]" in some other places of the code and was asked to use the part "^[A-Za-z0-9]" in a variable and use it so that it is not repetitive. The following is a modification to the above:
var regExPart= "^[A-Za-z0-9]";
var regExString = ("/" + regExPart+ "+$/".replace(/\"/g, "")); // replacing the quotes
var regExp = new RegExp(regExString); // results in /^[A-Za-z0-9]+$/
var valid = regExp.test(charValue); // charValue could be any keyvalue "a" or "#"
//the above returns false for "a"
//the above returns false for "#"
I am writing this in a keypress event to allow only alpha numeric
keypressValidation: function (e) {
var charCode = (e.which) ? e.which: event.keyCode;
var charValue = String.fromCharCode(charCode);
var valid = return /^[A-Za-z0-9]+$/.test(charValue);
if (!valid)
{
//prevent default (don't allow/ enter the value)
}
Not sure why. What am I missing in this. Need to return true for "a" and false for "#" for both the approaches. Any help/ suggestion would be of great help. Thank in advance.
For the RegExp class constructor, you do not need to specify forward slashes /.
var regExPart= "^[A-Za-z0-9]";
var regExp = new RegExp(regExPart + "+$"); // results in /^[A-Za-z0-9]+$/
console.log('a', regExp.test('a'))
console.log('#', regExp.test('#'))
It is not a must to contain '/'s in regexp
new RegExp("^[0-9a-zA-Z]$").test('a')
return true
new RegExp("^[0-9a-zA-Z]$").test('#')
return false
So just do
var rex="^[0-9a-zA-Z]$"
And you can use it anywhere. Tested in Chrome console.
I've made an example using your regex of what it should do, i think the way you were building your regex was not helping. You don't need to create a string and then create a new regex object , you can use /regex part/.
Anyways here is a working example.
function keypress(e) {
// Get the current typed key
var keynum = e.key;
// this regex only allow character between a and z and 0 and 9
var regex = /^[a-zA-Z0-9]+$/;
// we check if the current key matches our regex
if(!keynum.match(regex) ) {
// it doesn't ? well we stop the event from happening
e.preventDefault();
}
}
<input type="text" onkeypress="keypress(event)">
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
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/
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!');
}
This method is to prevent users from entering anything but numbers and "allowed characters." Allowed characters are passed as the parameter allowedchars.
So far, the method prevents number entries but the allowedchars doesn't work (tried with passing "-" (hyphen) and "." (period)). So I'm assuming my dynamic regex construction isn't correct. Help?
Thanks in advance!
numValidate : function (evt, allowedchars) {
var theEvent, key, regex,
addToRegex = allowedchars;
theEvent = evt || window.event;
key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = new RegExp('/^[0-9' + addToRegex + ']$/');
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
}
}
(ps. jQuery solutions are fine too)
1. When you construct via new RegExp, there's no need to include the surrounding /s.
var regex = new RegExp('^[0-9' + addToRegex + ']$');
2. But if addToRegex contains ] or -, the resulting regex may become invalid or match too much. So you need to escape them:
var regex = new RegExp('^[0-9' + addToRegex.replace(/([\-\]])/g, '\\$1') + ']$');
3. But since you are checking against 1 character anyway, it may be easier to avoid regex.
var pass = ("0123456789" + addToRegex).indexOf(key);
if (pass == -1) {
...