Regular Expression: Allow only characters a-z, A-Z - javascript

ExtJS 5.1
Let's say I have an example like that, I want user's name-surname so I don't want any numbers or special chars, I tried so many possibilities but couldn't make it:
var controller=this;
var refs = controller.getReferences();
var exp = '/^([^0-9]*)$/';
onButtonClick: function(button, e, eOpts) {
if(refs.nameSurname.value.match(exp)){
Ext.Msg.alert('ERROR', 'BlaBla');
}
}
With this code, I have no error when i enter a number to text field...
Thank you.

Assuming you need to actually match a string that has no digits...
You should not enclose the regex literal with single quotes, remove them. You do not need the capture group, you can remove ( and ).
Use
var exp = /^[^0-9]*$/;
Now, to check if a string matches a regex, you will be safer using a RegExp#test().
See the demo below:
var refs_nameSurname = "Som8ehere";
if(!(/^[^0-9]*$/.test(refs_nameSurname))){
console.log('ERROR');
}
However, you can reverse the logic, and show an error once a digit is found inside a string (simpler!):
var refs_nameSurname = "Somehere12";
if(/[0-9]/.test(refs_nameSurname)){
console.log('ERROR');
}

Related

JS - Nothing to repeat In match function

The error is simple. In JS I try to do somtehing to similar a preg_match in PHP. I found match function. I use this function to compare a value with strings elements. If found something return true, else return false.
I tried this
var sim_action = $(this);
if(sim_action.data("phone").toString().match("/^(+34|0034|34)+([67]){8})$/")){
But return this error.
Invalid regular expression: //^(+34|0034|34)+([67]){8})$//: Nothing
to repeat
So the question is. How can i add this string in JS match function?
You need to escape the + characters with a backslash: /^(\+34|0034|34)\+([67]){8})$/. You also have a closing bracket which doesn't have a matching opening bracket.
+ and () are metacharacters and if you want to refer to the literal, you need to escape them with a \. Here's a regex101 demo which highlights the errors with your regex
As for the regex, from wikipedia, I gather that spanish phone numbers have the format +34(6|7)xxxxxxxx
You can use this regex: /^(\+34|0034|34)[67]\d{8}$/
If you just want to check if the regex passes , you can use regex.test(<stringToBeTested>)
const regex = /^(\+34|0034|34)[67]\d{8}$/
const phone = "+34712345673";
if (regex.test(phone))
console.log("Valid phone number")
const phoneNumbers = ["+34712345673", "0034612345673", "+34812345673"]
phoneNumbers.forEach(p => console.log(regex.test(p)))

Regex not working properly in Javascript code

I have a JavaScript function that fires successfully on the onkeypress/onkeyup event for an asp.net textbox control as follows:
<asp:TextBox ID="txtboxLatestTag" runat="server" onkeypress="validate()" onkeyup="validate()"></asp:TextBox>
function validate() {
var str = $("#txtboxLatestTag").val();
var pattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}/gm
if (!str.match(pattern))
{
document.getElementById("txtboxLatestTag").style.color = "red";
}
else
{
document.getElementById("txtboxLatestTag").style.color = "white";
}
The regex is supposed to match entries in the format of:
10.10.10.10 or
1.1.1.1
or anything allowing 1 to 2 digits between each "." character.
This works, however the problem is that it ALSO matches with
1.1.1.100 i.e. it should not allow 3 numbers at the end of the string, only 2.
This works perfectly in regexr.com but I cannot figure out why it is matching on this.
Thank you
I believe what you want to do to exclude extra characters at the end of the string is add in the end of input character $ (or end-of-line character, since you're using multiline mode). This will cause extra characters at the end to invalidate the match. For example:
var oldPattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}/gm;
console.log("Old pattern match:");
console.log("10.10.10.100".match(oldPattern));
var pattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}$/gm;
console.log("New pattern match:");
console.log("10.10.10.100".match(pattern));
console.log("10.10.10.1".match(pattern));

Match a string if it comes after certain string

I need a regular expression for JavaScript to match John (case insensitive) after Name:
I know how to do it, but I don't know how to get string from a different line like so (from a textarea):
Name
John
This is what I tried to do :: var str = /\s[a-zA-Z0-9](?= Name)/;
The logic: get a string with letter/numbers on a linespace followed by Name.
Then, I would use the .test(); method.
EDIT:
I tried to make the question more simple than it should have been. The thing I don't quite understand is how do I isolate "John" (really anything) on a new line followed by a specific string (in this case Name).
E.g., IF John comes after Name {dosomething} else{dosomethingelse}
Unfortunately, JavaScript doesn't support look-behinds. For something this simple, you can just match both parts of the string like this:
var str = /Name\s+([a-zA-Z0-9]+)/;
You then just have to extract the first capture group if you want to get John. For example:
"Name\n John".match(/Name\s+([a-zA-Z0-9]+)/)[1]; // John
However if you're just using .test, the capture group isn't necessary. For example:
var input = "Name\n John";
if (/Name\s+[a-zA-Z0-9]+/.test(input)) {
// dosomething
} else{
// dosomethingelse
}
Also, if you need to ensure that Name and John appear on separate lines with nothing but whitespace in between, you can use this pattern with the multi-line (m) flag.
var str = /Name\s*^\s*([a-zA-Z0-9]+)/m;
You do not need a lookahead here, simply place Name before the characters you want to match. And to enable case-insensitive matching, place the i modifier on the end of your regular expression.
var str = 'Name\n John'
var re = /Name\s+[a-z0-9]+/i
if (re.test(str)) {
// do something
} else {
// do something else
}
Use the String.match method if you want to extract the name from the string.
'Name\n John'.match(/Name\s+([a-z0-9]+)/i)[1];
The [1] here refers back to what was matched/captured in capturing group #1

Regex is confusing me and why won't it parse properly?

Sorry about the confusing title. I'm new to Regex and JS/JQ in general. However, I'm trying to parse this. Basically, I want it to add the key pressed to the HTML if and ONLY if the keys 0-9 and the keys +, -, /, and * are pressed. Any help would be much appreciated. Here is my code:
function charCode(code) {
return String.fromCharCode(code);
}
function escapeChars(esc) {
return esc.replace(/[0-9\+-\*\/]*$/, "");
}
$('#tb').html("0");
$(document).on("keydown", function(event) {
var div = $('#tb');
var which = event.which;
which = charCode(which);
which = escapeChars(which);
else if (div.html() == "0") {
//alert("Div is equal to 0."); --Debug
div.html(which);
} else {
//alert("Div is equal to " + div.html()); --Debug
div.html(div.html() + which);
}
});
Currently, it doesn't allow anything through.
There's a couple problems with your regular expression.
You want to replace characters that do not match your list. To do that, you start your character class ([]) with a ^.
You don't need to escape + or * in the regular expression. You do need to move the - to the beginning or end though.
You don't need the * or the $ after the character class. Dropping those, you'll replace any character that doesn't match, no matter where it occurs in the string.
In case your string contains more than one character (may not apply here), adding a g flag to the end will allow you to replace all characters that do not match.
That results in a regular expression that looks like this:
/[^0-9+*\/-]/g
This fiddle shows the above regular expression working: http://jsfiddle.net/WyttT/
Updated
Another problem you're encountering is caused by checking keycodes from a keydown event. The keycodes on keydown do not match to actual ascii character codes, so non-alphanumeric keys are getting converted into weird characters. If you change your even handler to respond tokeypress instead, you'll get better results.
I don't think you want a regex for this. I think charAt() will do what you want far more simply.
You have a character. You have a list of characters which either match it or don't. charAt() does that simply and efficiently.
Now that jcsanyi has helped you with the regex, here is a simplification of your JS code. Codepen
You will want to use keypress instead of keydown/keyup, otherwise your numpad will return the wrong keys, and anything requiring a shift (shift+8 = * for instance) won't work. You can also use RegExp.test(String) to check if the character is valid, and div.append(char) in place of div.html(div.html + char).
var div = $('#tb');
$(document).on("keypress", function(event) {
var char = String.fromCharCode(event.which);
if (/[0-9+*\/-]/.test(char) === true) {
div.append(char);
}
});

jQuery input filter for textarea

I adapted this solution into my script. The idea is to prevent the user from typing unauthorized characters (of course there is also a filter on the back end).
$('#someinput').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
console.log(str);
return '';
}))
})
It works nice, but I also need the users to be able to type specific allowed characters like: .,!?ñáéíóú - I mean, the basic a-zA-Z0-9 plus some basic chars and the whole bunch of special language characters.
What actually needs to be left out are: ##$%^&*()=_+"':;/<>\|{}[]
Any ideas? Thanks!
Solution thanks to Michael
//query
$('#someinput').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
setTimeout(function() {
$('#someinput').val($('#someinput').val().replace(/[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
$('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
},100);
});
Invert your regular expression to only replace the specific characters you want omitted:
$th.val( $th.val().replace(/\s?[##$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars
Note, a few of them need to be escaped with a backslash inside a [] character class: \\\[\]\^\/
If I'm understanding what you are wanting to do, can't you just add those unwanted characters to your regex instead of doing the [^a-zA-Z0-9]?
Replace that with [##\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]] (notice the escaping)

Categories

Resources