Add limited spaces depend on name in regular expression using JavaScript - javascript

I have one regular expression for Full Name Validation,but I want name should start with alphabates and space (it depends on name) with limit like 50 (not more than 50):
^[a-zA-Z ]*$
This is working but but here no limit, how to add limit and spaces (depends on name)?

To force the first symbol to be an English letter or a space, and the following 49 characters can be any (but a newline), you can use the following regex:
^[a-zA-Z ].{49}$
If you want to just limit the input to English letters and spaces, you just need to add the limiting quantifier {1,50} meaning from 1 up to 50 occurrences of the preceding subpattern:
^[a-zA-Z ]{1,50}$
Adapting to your code and coding style, here is how you can use the second regex:
if($(this).attr('id') === "FullName") {
var re = new RegExp("^[a-zA-Z ]{1,50}$");
if(!re.test($(this).val())) {
res = "FullName is Not Valid"; alertDispaly(res);
}
}
To apply further restrictions, e.g. do not end in a space, you can use ^[a-zA-Z ]{1,49}[a-zA-Z]$. Or, no double space allowed: ^(?!.* )[a-zA-Z ]{1,49}[a-zA-Z]$.
EDIT: To allow tabs, newline characters, and other whitespace, you can add \\s to your pattern, e.g.:
var re = new RegExp("^[a-zA-Z\\s]{1,50}$");
You need to use \s in literal regex notation, and \\s in a RegExp constructor.

If you want to limit the name to max 50 characters:
^[a-zA-Z\s]{,50}$
Here {,50} will match for maximum of 50 preceding characters.
\s will match any space character.
EDIT
var reg = /^[a-zA-Z\s]{1,50}$/;
....
if (reg.test($(this).val())) {
// Valid
} else {
// Invalid
}
Demo: http://jsfiddle.net/tusharj/xcr2hgk9/

You can try:
^[a-zA-Z\s]{0,50}$
http://regexr.com/3b3o2

Related

How to convert a camelcased string to sentence cased without excluding any special characters?

How to convert a camelcased string to sentence cased without excluding any special characters?
Suggest a regex for converting camelcased string with special characters and numbers to sentence case?:
const string = `includes:SummaryFromDetailHistory1990-AsAbstract`
Expected outcome:
Includes : Summary From Detail History 1990 - As Abstract
Currently I'm using lodash startCase to convert camelCased to sentenceCase. But the issue with this approach is that it is removing special characters like brackets, numbers, parenthesis, hyphens, colons, etc... (most of the special characters)
So the idea is to convert camelcased strings to sentence cased while preserve the string identity
For example:
const anotherString = `thisIsA100CharactersLong:SampleStringContaining-SpecialChar(s)10&20*`
const expectedReturn = `This Is A 100 Characters : Long Sample String Containing - Special Char(s) 10 & 20 *`
Is that possible with regex?
You'll have to deal with all the cases yourself:
[a-z](?=[A-Z]): lowercase followed by uppercase
[a-zA-Z](?=[0-9]): letter followed by digit
[0-9](?=[a-zA-Z]): digit followed by letter
[a-zA-Z0-9](?=[^a-zA-Z0-9]): letter or digit followed by neither letter nor digit (\w and \W could be used, but they cover _ too, so up to you)
[^a-zA-Z0-9](?=[a-zA-Z0-9]): not letter nor digit following by either letter or digit
etc.
Then, you can or them together:
([a-z](?=[A-Z])|[a-zA-Z](?=[0-9])|[0-9](?=[a-zA-Z])|[a-zA-Z0-9](?=[^a-zA-Z0-9])|[^a-zA-Z0-9](?=[a-zA-Z0-9]))
And replace by:
$1
(see the space after $1).
See https://regex101.com/r/4AVbAs/1 for instance.
You will hit edge cases though, e.g. Char(s), so you'll need special rules for the parens for instance (see the following section about lookbehinds that can help for that). A bit of a tough job, quite error prone too and hardly maintainable I'm afraid.
If lookbehinds were allowed, you would not need to capture the first char in each group, but wrap the left patterns in (?<=...) and replace by a simple space directly:
(?<=[a-z])(?=[A-Z]): preceded by lowercase, followed by uppercase
(?<=[a-zA-Z])(?=[0-9]): preceded by letter, followed by digit
(?<=[0-9])(?=[a-zA-Z]): preceded by digit, followed by letter
(?<=[a-zA-Z0-9])(?=[^a-zA-Z0-9])(?!(?:\(s)?\)): preceded by letter or digit, followed by not letter nor digit, as well as not followed by (s) nor )
(?<=[^a-zA-Z0-9])(?<!\()(?=[a-zA-Z0-9]): preceded by not letter nor digit, as well as not preceded by (, followed by letter or digit
or-ed together:
(?<=[a-z])(?=[A-Z])|(?<=[a-zA-Z])(?=[0-9])|(?<=[0-9])(?=[a-zA-Z])|(?<=[a-zA-Z0-9])(?=[^a-zA-Z0-9])(?!(?:\(s)?\))|(?<=[^a-zA-Z0-9])(?<!\()(?=[a-zA-Z0-9])
Replace with an empty space, see https://regex101.com/r/DB91DE/1.
The wanted result doesn't seem to be regular, some special characters are supposed to be preceeded with a space and some are not. Treating the parenthesis like you want is a bit tricky. You can use function to handle the parenthesis, like this:
let parenth = 0;
const str = `thisIsA100CharactersLong:SampleStringContaining-SpecialChar(s)10&20*`,
spaced = str.replace(/[A-Z]|\d+|\W/g, (m) => {
if (m === '(') {
parenth = 1;
return m;
}
if (parenth || m === ')') {
parenth = 0;
return m;
}
return ` ${m}`;
});
console.log(spaced);
If the data can contain other brackets, instead of just checking parentheses, use a RexExp to test any opening bracket: if (/[({[]/.test(m)) ..., and test for closing brackets: if (/[)}\]]/.test(m)) ....
You can test the snippet with different data at jsFiddle.
This is impossible. You cannot do this in regex. You will have to consider exceptions...

Regex to reject names ending in non-letters except dot

I have written a regex that returns true or false depending on whether the text provided is a valid first/last name:
let letters = `a-zA-Z`;
letters += `àáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšž`;
letters += `ÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð`;
const re = new RegExp(`^[${letters}][${letters} ,.'’-]+[${letters}.]$`, 'u')
return(name.match(re));
So far, I'm able to ensure it only validates names that actually start with a letter and do not contain numerals or any special characters other than dot, hyphen, or comma. However, it still rejects names like Jo and Xi. I understand it's due to the three separate $-blocks. But the blocks are there to ensure the name doesn't start with a non-letter or end in a non-letter other than dot. How should I modify my expression to accommodate this?
Also, is there any way to shorten this expression without compromising its range? I still need it to cover extended Latin characters.
If the minimum length of the word is 2 chars, you could use a negative lookahead ^(?!.*[ ,'’]$) to assert that the string does not end with the characters that you would not allow and leave out the last [${letters}.]
Regex demo
If the minimum length is 1, you could use another negative lookahead (?![ .,'’]) and add the dot as well so that a single dot is not allowed at the beginning and then use the single character class that contains all allowed characters.
^(?!.*[ ,'’]$)(?![ .,'’])[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'’-]+$
Regex demo

Regular expression for validating with specific characters through javascript

I want to validate a string that does not allows the following characters.
<,>,:,","/,\,|,?,*,#
I want to validate this through JavaScript.
I was trying this with the following code.
var reg = /[^a-zA-Z0-9 \-_]+/;
reg.test(filename[0])
But this was unable to validating the symbol #.
Please help.
The problem you have is that you included the hyphen in the middle of the pattern without escaping it. This tells the engine that you are expecting a range--in this case space through underscore. It's easier (in my opinion) to place the hyphen as either the first or last character in the pattern, at which point you don't have to escape it. (It would be the second character if you are using a negated character class.)
e.g.
var reg = /[^a-zA-Z0-9 \-_]+/;
--OR--
var reg = /[^a-zA-Z0-9 _-]+/;
--OR--
var reg = /[^-a-zA-Z0-9 _]+/;
Do you only want to allow English letters a-z (and A-Z), numbers, the space, '_', and '-'? If so, that is different than disallowing the characters you specified since '☃' doesn't have the characters you provided but may not be a valid string in your use case.
In the case you just want the English alphabet, numbers, space, '_', and '-', you can use the following RegExp and conditional:
var reg = /^[a-zA-Z0-9 \-_]+$/;
if (reg.test(filename[0])) {
// String is ok
}
This says everything in the string between beginning (^) and end ($) must be one or more of the allowed characters.
If you want to disallow the characters you provided in your question, you can use:
var reg = /[\<\>\:\,\/\\\|\?\*\#]/;
if (!reg.test(filename[0])) {
// String is ok
}
This says to search for any of the characters you've listed (they are all escaped with a \ before them) and if you find any, the string is invalid. So only if the test fails is the string a valid string - that's why there's a ! before the test.
string sourceString ="something" ;
var outString = sourceString.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');

RegExp issues - character limit and whitespace ignoring

I need to validate a string that can have any number of characters, a comma, and then 2 characters. I'm having some issues. Here's what I have:
var str="ab,cdf";
var patt1=new RegExp("[A-z]{2,}[,][A-z]{2}");
if(patt1.test(str)) {
alert("true");
}
else {
alert("false");
}
I would expect this to return false, as I have the {2} limit on characters after the comma and this string has three characters. When I run the fiddle, though, it returns true. My (admittedly limited) understanding of RegExp indicates that {2,} is at least 2, and {2} is exactly two, so I'm not sure why three characters after the comma are still returning true.
I also need to be able to ignore a possible whitespace between the comma and the remaining two characters. (In other words, I want it to return true if they have 2+ characters before the comma and two after it - the two after it not including any whitespace that the user may have entered.)
So all of these should return true:
var str = "ab, cd";
var str = "abc, cd";
var str = "ab,cd";
var str = "abc,dc";
I've tried adding the \S indicator after the comma like this:
var patt1=new RegExp("[A-z]{2,}[,]\S[A-z]{2}");
But then the string returns false all the time, even when I have it set to ab, cd, which should return true.
What am I missing?
{2,} is at least 2, and {2} is exactly two, so I'm not sure why three characters after the comma are still returning true.
That's correct. What you forgot is to anchor your expression to string start and end - otherwise it returns true when it occurs somewhere in the string.
not including any whitespace: I've tried adding the \S indicator after the comma
That's the exact opposite. \s matches whitespace characters, \S matches all non-whitespace characters. Also, you probably want some optional repetition of the whitespace, instead of requiring exact one.
[A-z]
Notice that this character range also includes the characters between Z and a, namely []^_`. You will probably want [A-Za-z] instead, or use [a-z] and make your regex case-insensitive.
Combined, this is what your regex should look like (using a regular expression literal instead of the RegExp constructor with a string literal):
var patt1 = /^[a-z]{2,},\s*[a-z]{2}$/i;
You are missing ^,$.Also the range should be [a-zA-Z] not [A-z]
Your regex should be
^[a-zA-Z]{2,}[,]\s*[A-Za-z]{2}$
^ would match string from the beginning...
$ would match string till end.
Without $,^ it would match anywhere in between the string
\s* would match 0 to many space..

Regular Expression for alphabets with spaces

I need help with regular expression. I need a expression which allows only alphabets with space for ex. college name.
I am using :
var regex = /^[a-zA-Z][a-zA-Z\\s]+$/;
but it's not working.
Just add the space to the [ ] :
var regex = /^[a-zA-Z ]*$/;
This is the better solution as it forces the input to start with an alphabetic character. The accepted answer is buggy as it does not force the input to start with an alphabetic character.
[a-zA-Z][a-zA-Z ]+
This will allow space between the characters and not allow numbers or special characters. It will also not allow the space at the start and end.
[a-zA-Z][a-zA-Z ]+[a-zA-Z]$
This will accept input with alphabets with spaces in between them but not only spaces. Also it works for taking single character inputs.
[a-zA-Z]+([\s][a-zA-Z]+)*
Special Characters & digits Are Not Allowed.
Spaces are only allowed between two words.
Only one space is allowed between two words.
Spaces at the start or at the end are consider to be invalid.
Single word name is also valid : ^[a-zA-z]+([\s][a-zA-Z]+)*$
Single word name is in-valid : ^[a-zA-z]+([\s][a-zA-Z]+)+$
Regular expression starting with lower case or upper case alphabets but not with space and can have space in between the alphabets is following.
/^[a-zA-Z][a-zA-Z ]*$/
This worked for me
/[^a-zA-Z, ]/
This will work too,
it will accept only the letters and space without any symbols and numbers.
^[a-zA-z\s]+$
^ asserts position at start of the string Match a single character
present in the list below [a-zA-z\s]
matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy) a-z matches a single
character in the range between a (index 97) and z (index 122) (case
sensitive) A-z matches a single character in the range between A
(index 65) and z (index 122) (case sensitive) \s matches any
whitespace character (equivalent to [\r\n\t\f\v ]) $ asserts position
at the end of the string, or before the line terminator right at the
end of the string (if any)
This worked for me, simply type in javascript regex validation
/[A-Za-z ]/
This one "^[a-zA-Z ]*$" is wrong because it allows space as a first character and also allows only space as a name.
This will work perfectly. It will not allow space as a first character.
pattern = "^[A-Za-z]+[A-Za-z ]*$"
This works for me
function validate(text) {
let reg = /^[A-Za-z ]+$/; // valid alphabet with space
return reg.test(text);
}
console.log(validate('abcdef')); //true
console.log(validate('abcdef xyz')); //true
console.log(validate('abc def xyz')); //true
console.log(validate('abcdef123')); //false
console.log(validate('abcdef!.')); //false
console.log(validate('abcdef#12 3')); //false
This will restrict space as first character
FilteringTextInputFormatter.allow(RegExp('^[a-zA-Z][a-zA-Z ]*')),
This will work for not allowing spaces at beginning and accepts characters, numbers, and special characters
/(^\w+)\s?/

Categories

Resources