Anybody can help me with regular expression which will only accept alphabetical letters from English alphabet and numbers without whitespaces ( ÖÜÕÖ and similar characters + whitespaces will break the HTML link this thing is creating )?
I currently have :
/[A-Za-z ]\S+$/
but this will allow whitespaces and ÖÜÄ and similar at the beggining.
function validatenumber(el) {
var regex = /[A-Za-z ]\S+$/;
if( !regex.test(el.value) ) {
alert('invalid value');
}else{
alert('correct value');
}
}
http://jsfiddle.net/qd7BL/1375/
Here's a fiddle.
Try
/^\w+$/
It'll allow only a non empty string, containing english alphabet letter, both cases, underscore and digits in a string.
/^[A-Za-z0-9]+$/
Solved the problem, although I should probably think is more through as much more elements are allowed in link.
Also, the best solution was to use Slugify, a plugin for jQuery which will make the input correct format.
Related
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;
}
}
I have strings which contains thousand separators, however no string-to-number function wants to consume it correctly (using JavaScript). I'm thinking about "preparing" the string by stripping all thousand separators, leaving anything else untoched and letting Number/parseInt/parseFloat functions (I'm satisfied with their behavious otherwise) to decide the rest. But it seems what i have no idea which RegExp can do that!
Better ideas are welcome too!
UPDATE:
Sorry, answers enlightened me how badly formulated question it is. What i'm triyng to achieve is: 1) to strip thousand separators only if any, but 2) to not disturb original string much so i will get NaNs in the cases of invalid numerals.
MORE UPDATE:
JavaScript is limited to English locale for parsing, so lets assume thousand separator is ',' for simplicity (naturally, it never matches decimal separator in any locale, so changing to any other locale should not pose a problem)
Now, on parsing functions:
parseFloat('1023.95BARGAIN BYTES!') // parseXXX functions just "gives up" on invalid chars and returns 1023.95
Number('1023.95BARGAIN BYTES!') // while Number constructor behaves "strictly" and will return NaN
Sometimes I use rhw loose one, sometimes strict. I want to figure out the best approach for preparing string for both functions.
On validity of numerals:
'1,023.99' is perfectly well-formed English number, and stripping all commas will lead to correct result.
'1,0,2,3.99' is broken, however generic comma stripping will give '1023.99' which is unlikely to be a correct result.
welp, I'll venture to throw my suggestion into the pot:
Note: Revised
stringWithNumbers = stringwithNumbers.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");
should turn
1,234,567.12
1,023.99
1,0,2,3.99
the dang thing costs $1,205!!
95,5,0,432
12345,0000
1,2345
into:
1234567.12
1023.99
1,0,2,3.99
the dang thing costs $1205!!
95,5,0432
12345,0000
1,2345
I hope that's useful!
EDIT:
There is an additional alteration that may be necessary, but is not without side effects:
(\b\d{1,3}),(?=\d{3}(\D|$))
This changes the "one or more" quantifier (+) for the first set of digits into a "one to three" quantifier ({1,3}) and adds a "word-boundary" assertion before it. It will prevent replacements like 1234,123 ==> 1234123. However, it will also prevent a replacement that might be desired (if it is preceded by a letter or underscore), such as A123,789 or _1,555 (which will remain unchanged).
A simple num.replace(/,/g, '') should be sufficient I think.
Depends on what your thousand separator is
myString = myString.replace(/[ ,]/g, "");
would remove spaces and commas.
This should work for you
var decimalCharacter = ".",
regex = new RegExp("[\\d" + decimalCharacter + "]+", "g"),
num = "10,0000,000,000.999";
+num.match(regex).join("");
To confirm that a numeral-string is well-formed, use:
/^(\d*|\d{1,3}(,\d{3})+)($|[^\d])/.test(numeral_string)
which will return true if the numeral-string is either (1) just a sequence of zero or more digits, or (2) a sequence of digits with a comma before each set of three digits, or (3) either of the above followed by a non-digit character and who knows what else. (Case #3 is for floats, as well as your "BARGAIN BYTES!" examples.)
Once you've confirmed that, use:
numeral_string.replace(/,/g, '')
which will return a copy of the numeral-string with all commas excised.
You can use s.replaceAll("(\\W)(?=\\d{3})","");
This regex gets all alpha-numeric character with 3 characters after it.
Strings like 4.444.444.444,00 € will be 4444444444,00 €
I have used the following in a commercial setting, and it has worked often:
numberStr = numberStr.replace(/[. ,](\d\d\d\D|\d\d\d$)/g,'$1');
In the above example, thousands can be marked with a decimal, a comma, or a space.
In some cases ( like a price of 1000,5 Euros) the above doesn't work. If you need something more robust, this should work 100% of the time:
//convert a comma or space used as the cent placeholder to a decimal
$priceStr = $priceStr.replace(/[, ](\d\d$)/,'.$1');
$priceStr = $priceStr.replace(/[, ](\d$)/,'.$1');
//capture cents
var $hasCentsRegex = /[.]\d\d?$/;
if($hasCentsRegex.test($priceStr)) {
var $matchArray = $priceStr.match(/(.*)([.]\d\d?$)/);
var $priceBeforeCents = $matchArray[1];
var $cents = $matchArray[2];
} else{
var $priceBeforeCents = $priceStr;
var $cents = "";
}
//remove decimals, commas and whitespace from the pre-cent portion
$priceBeforeCents = $priceBeforeCents.replace(/[.\s,]/g,'');
//re-create the price by adding back the cents
$priceStr = $priceBeforeCents + $cents;
I need to make a string starts and ends with alphanumeric range between 5 to 20 characters and it could have a space or none between characters. /^[a-z\s?A-Z0-9]{5,20}$/ but this is not working.
EDIT
test test -should pass
testtest -should pass
test test test -should not pass
You can't do this with traditional regex without writing a ridiculously long expression, so you need to use a look-ahead:
/^(?=(\w| ){15,20}$)\w+ ?\w+$/
This says, make sure there are between 15 and 20 characters in the match, then match /\w+ \w+/
Note I used \w for simplification. It is the same as your character class above except it also accepts underscores. If you don't want to match them you have to do:
/^(?=[a-zA-Z0-9 ]{15,20}$)[a-zA-Z0-9]+ ?[a-zA-Z0-9]+$/
You can't put a ? inside of [...]. [...] is used to specify a set of characters precisely, you can't maybe (?) have a character inside a set of characters. The occurrence of any specific characters is already optional, the ? is meaningless.
If you allow any number of spaces inside your match, just remove the question mark. If you want to allow a single space but no more, then regular expressions alone can't do that for you, you'd need something like
if (myString.match(/^[a-z\sA-Z0-9]{5,20}$/ && myString.match(/\s/g).length <= 1)
You couldn't do this with a single traditional regex without it being dozens of lines long; regexes are meant for matching more simpler patterns than this.
If you only want to use regexes, you could use two instead of one. The first matches the general pattern, the second ensures that only one non-space characters is found.
if (myString.match(/^[a-z\sA-Z0-9]{5,20}$/ && myString.match(/^[^\s]*\s?[^\s]*$/))) {
Example Usage
inputs = ["test test", "testtest", "test test test"];
for (index in inputs) {
var myString = inputs[index];
if (myString.match(/^[a-z\sA-Z0-9]{5,20}$/ && myString.match(/^[^\s]*\s?[^\s]*$/))) {
console.log(myString + " matches.")
} else {
console.log(myString + " does not match.")
}
}
This produces the output specified in your question.
Meh , So here's the ridiculously long traditional regex for the same
(?i)[a-z0-9]+( [a-z0-9]+)?{5,12}
js vesrion (w/o the nested quantifier)
/^([a-z0-9]( [a-z0-9])?){5,12}$/i
Trying to check input against a regular expression.
The field should only allow alphanumeric characters, dashes and underscores and should NOT allow spaces.
However, the code below allows spaces.
What am I missing?
var regexp = /^[a-zA-Z0-9\-\_]$/;
var check = "checkme";
if (check.search(regexp) == -1)
{ alert('invalid'); }
else
{ alert('valid'); }
However, the code below allows spaces.
No, it doesn't. However, it will only match on input with a length of 1. For inputs with a length greater than or equal to 1, you need a + following the character class:
var regexp = /^[a-zA-Z0-9-_]+$/;
var check = "checkme";
if (check.search(regexp) === -1)
{ alert('invalid'); }
else
{ alert('valid'); }
Note that neither the - (in this instance) nor the _ need escaping.
This is the most concise syntax I could find for a regex expression to be used for this check:
const regex = /^[\w-]+$/;
You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:
var regexp = /^[a-zA-Z0-9-_]+$/;
Got stupid error. So post here, if anyone find it useful
[-\._] - means hyphen, dot and underscore
[\.-_] - means all signs in range from dot to underscore
Try this
"[A-Za-z0-9_-]+"
Should allow underscores and hyphens
try this one, it is working fine for me.
"^([a-zA-Z])[a-zA-Z0-9-_]*$"
Don't escape the underscore. Might be causing some whackness.
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.