javascript : problem with regular expression - javascript

I'm trying to validate the value of an input text field with the following code:
function onBlurTexto(value) {
var regexNIT = "([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])";
regexCompilado = new RegExp(regexNIT);
if (!(regexCompilado.test(value))) {
alert("Wrong character in text :(");
return false;
} else {
return true;
}
}
But when i enter this text:
!65a
the function returns true (as you can see, the "!" character does not exist in the regular expression)
I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp.
How can i put this regular expression to work?
Thanks in advance.
EDIT
i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. I modified the sample. Thanks #TecBrat

You should provide the start (^) and end ($) flags to your regex. Now you are matching 65a since you have alternate sets.
This should work /^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$/g
Demo: https://regex101.com/r/zo2MpN/3

RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. In order to do the latter, you need to add start and end anchors to your regex (i.e. '^' at the start and '$' at the end, so you have "^your regex here$").
I also just noticed that your regex is currently matching only one character. You probably want to add a '+' after the parens so that it matches one or more:
"^([a-zA-z]|[0-9]|[&#,#.ÑñáéíóúÁÉÍÓÚ\|\s])+$"

This is wrong. the variable you use doesn't has anything. Try this instead.
var regexCompilado = new RegExp(regexNIT);

Related

Regex return undefined in a JavaScript String

I have a little code snippet where I use Regular Expressions to rip off punctuation, numbers etc from a string. I am getting undefined along with output of my ripped string. Can someone explain whats happening? Thanks
var regex = /[^a-zA-z\s\.]|_/gi;
function ripPunct(str) {
if ( str.match(regex) ) {
str = str.replace(regex).replace(/\s+/g, "");
}
return str;
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));
You should pass a replacement pattern to the first replace method, and also use A-Z, not A-z, in the pattern. Also, there is no point to check for a match before replacing, just use replace directly. Also, it seems the second chained replace is redundant as the first one already removes whitespace (it contains \s). Besides, the |_ alternative is also redundant since the [^a-zA-Z\s.] already matches an underscore as it is not part of the symbols specified by this character class.
var regex = /[^a-zA-Z\s.]/gi;
function ripPunct(str) {
return str.replace(regex, "");
}
console.log(ripPunct("*#£#__-=-=_+_devide-00000110490and586#multiply.edu"));

Regex: Check input string is not only upperccase and is not only lowercase

What is the regex to check if input string is NOT lowercase only, it is NOT uppercase only and does NOT contain numbers.
Validation must fail
SIMO TEST
SIMO344
simo
simo3432
These are ok
SIMO test
Simo
Welcome to Stackoverflow
When posting a question, please make sure to include your attempts, so that we can help guide you to an answer. This website is not meant to give you the answer, but to help guide you to an answer, or to explain your error. It's more rewarding to help you if we are simply guiding you and not giving you the answer. You'll probably get more response too. Please remember that when posting next time.
I tried to explain regular expressions in JavaScript, and tried to guide you through the logic in my answer.
Your case
You can use the .test function of a RegExp to test if a string matches a regular expression. You can then invert that result to check if the string does not contain it. Each of the cases you mentioned is a separate expression, which can be joined by the | operator.
Testing if a string is lowercase only:
In a RegExp, a - can be used to indicate a range of characters. There are already specially assigned codes for commonly used ranges, such as \s for a white space. The + operator means one or more. The ^ means starts at the beginning of the line(string) and $ means starting the end.
^[a-z\s]+$
Testing if a string is uppercase only:
This is the exact same as the lowercase case, but the character range is for uppercase letters:
^[A-Z\s]+$
Testing for digits
The regex code \d is short for a range of digits (you can essentially think of it as [0-9], but it also accounts for unicode).
\d
Putting it all together
^[a-z\s]+$|^[A-Z\s]+$|\d
And in a condition, it would be:
if (!/^[a-z\s]+$|^[A-Z\s]+$|\d/.test(your_string_here)) {
// the string isn't uppercase only, lowercase only
// and doesn't contain a digit
}
Please see the below code snippet. Modify as per your requirement.
function validate(strInput) {
var re = /\d/;
if(re.exec(strInput)===null){
re = /^(?!.*[a-z\d]).+$/;
if(re.exec(strInput)===null){
re = /^[A-Z][a-z]*/;
if(re.exec(strInput)!==null)
return re.exec(strInput);
}
}
return false;
};
console.log(validate("SIMO TEST"));
console.log(validate("SIMO344"));
console.log(validate("Simo"));
console.log(validate("simo"));
console.log(validate("simo3432"));
console.log(validate("SIMO2 TEST"));
console.log(validate("Simo3"));
console.log(validate("SIMO test"));
function CheckPassword() {
var inputtxt = $('#text12').val();
console.log(inputtxt)
var passw = /(?=.*[a-z])(?=.*[A-Z]).{6,20}$/;
var passWN = /\d/;
if (inputtxt.match(passw)) {
if (!inputtxt.match(passWN)) {
alert('Correct, try another...')
return true;
} else {
alert('Wrong...!')
return false;
}
} else {
alert('Wrong...!')
return false;
}
}

How would I make a regular expression that would mean /some string/ either followed by a line break or not?

function(input){
return input.replace(/teststring/ig, "adifferentstring");
}
I want to replace "teststring" and "teststring\n" with "adifferentstring"
In regex, to match a specific character you can place it in brackets:
[\n]
To make the match "optional", you can follow it with a ?:
[\n]?
In your exact example, your full regex could be:
teststring[\n]?
So, your function would look like:
function replace(input) {
return input.replace(/teststring[\n]?/ig, "adifferentstring");
}
I'd suggest going with matching characters in brackets as this makes for easy expansion; consider, for instance, that you want to match Window's newlines (a carriage-return + a newline):
teststring[\r\n]?
Try
function(input){
return input.replace(/teststring\n?/ig, "adifferentstring");
}
Try .replace(/teststring[\n]?/ig,"adifferentstring");
It would be something like this:
var re = /teststring([\n]?)/ig;
So then your replace statement would look about like this:
return input.replace(re,"adifferentstring");
Here's a fiddle showing the regex works.
And then a fiddle showing the replace operation working.
Edit:
Actually, thinking about the problem a little further, if your regex does match a carriage return or new line character, that would need to get put back into the replacing string. The same regex I posted originally will work but you will need this replace statement instead (with the $1 denoting the first group in parantheses.
return input.replace(re,"adifferentstring$1");
fiddle

jQuery regexp validation

I would like to validate user input client side with a little jQuery function that is called onsubmit on my form. I want the field #fname (first name) to only allow a-z, A-Z and space. The return false is supposed to be stopping the form from submitting.
function validateregister(){
if (!($("fname") =~ [a-zA-Z ])) {
return false;
}
}
This is my HTML:
<input type="submit" value="Join now!" id="registersubmit" class="paddingoutline2" onsubmit="return validateregister()">
Of course, i'm going to validate the user input on the server side later on. When I submit the form, it gives me an "internal server error". This makes me think that I made an error in my function validateregister(). Is there anything wrong? If the I'm pretty new to jQuery so any help is appreciated.
Thanks!
What you want is
function validateregister(){
return /^[a-zA-Z ]+$/.test($('#fname').val());
}
Apart fixing the selector suggesting the use of the val and test functions, I took the liberty to change the regex :
^ and $ force the test to cover the whole string
the + requires at least one character
But are you aware that this regex might be too strict if you want people to type their real first name ? Yours, for example, would not pass...
You have to use regex this way:
function validateregister(){
var nameRgx = /[a-zA-Z]/;
var phoneRgx = /[0-9]/;
if (!nameRgx.test($("#fname").val())) {
return false;
}
if (!phoneRgx.test($("#phone").val())) {
return false;
}
}
And make sure to refer your elements with Either with # id notation or . class notation. In your code you are not referencing your elem in a proper way.
^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression;
also forces minimal matching when an expression might
match several strings within a search string.
More Info about Regex writing

How can I customize this javascript function?

I have this javascript function that block special characters...
function validaTexto(texto)
{
!(/^[A-zÑñ0-9]*$/i).test(texto.value) ? texto.value = texto.value.replace(/[^A-zÑñ0-9]/ig, '') : null;
}
The problem is that this function doesn't allow me to type blank spaces... how can I customize this function to allow me some other things, such as blank spaces, "," , "." , ";" and so on?
Thanks!!
change the regex to this:
!(/[^A-zÑñ0-9 ,\.;]*$/i)
also, the function is quite redundant in that it checks the string twice, basically saying "Does the string contain any of these characters? Yes? Ok, so search the string for these same characters and remove them. Just change it to this:
function validaTexto(texto) {
texto.value.replace(/[^a-zñ0-9 ,\.;]/ig, '');
}
function validaTexto(texto) {
texto.value.replace(/[^A-z0-9 ,\.;]/ig, '');
}
Referenes (with examples):
http://www.regular-expressions.info/
http://regexlib.com/
Read this post:
Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)
With a bit of effort, you should be able to modify your regex to do what you need.

Categories