REGEX to match only VALID EXCEL COLUMNS (A-XFD) - javascript

Ok, I have ANOTHER REGEX question for everyone.
I have a field that has multiple validation steps. The first step is to ensure it isn't blank, second is to ensure that only between 1 and 3 CAPITAL LETTERS are entered, and third, to ensure it doesn't contain "[" (an opening bracket will denote a function in this scenario and we skip validation). All of this works. Now, I have to ensure that the value being entered is only a valid Excel Column Reference. Valid Excel Columns can be the letters A - XFD.
I am currently using:
if (checkValue !==""){ //check for not blank
if ((checkValue.match(/^[A-Z]{1,3}$/) === null) && (functionCheck === false) && (validateColumnRange(rangeFrom))) { //check for only 1 - 3 alpha chars & run function check (function looks for "["), and run function check to validate column range
//do A - XFD validation here
}
}
any further direction will be much appreciated as I have been through regex tuts for hours now and am lost.
I had been given help on a similar issue in the past and my poor attempt to emulate the function that was provided then is as follows:
function validateColumnRange(valueRange) {
if (typeof valueRange !== "string" || !valueRange.length)
return false;
var startIndex = valueRange.search(/[\d+]/);
var column = valueRange.substring(0, startIndex).toUpperCase();
return (column >= "A" && column <= "XFD");
}
it doesn't work...please help

Since you've already determined that the value is 1-3 alphabetic characters, how about:
(column.length < 3 || column <= "XFD")
Any value with 2 or less letters should be acceptable, and for the case of three letters, alphabetic comparison is adequate.

Use this regex expression:
/^[A-XFD]+$/

Related

Using typeof operator in JS correctly?

I am making a simple hangman game in JavaScript. I'm playing around trying to add new features and one of the features I'd like to add is to check the input the user gives (when they guess a letter of the unknown word) to make sure it is in fact an alphanumeric input (or my intention is to check that the input isn't a symbol like "!" or a number like "5").
I know I could probably use a global variable that contains all the valid characters and check the input against those characters but I was wondering if there is a built in method for this. I found the typeof operator but it seems that the types of characters I'm checking for get converted to strings by JavaScript.
The loop in which I'm trying to implement this:
while (remainingLetters > 0 && numberOfGuesses > 0) {
alert(answerArray.join(" "));
alert("You have " + numberOfGuesses + " guesses remaining.");
var guess = prompt("Guess a letter, or click \
'Cancel' to stop playing.").toLowerCase();
if (guess === null) {
break;
} else if (typeof guess === "number") {
alert("Please enter a single LETTER.");
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
// there is some code missing here that I'm pretty sure is not essential
// to my question!
When I run that in Chrome's dev tools, I can input "2" and it never gives me the alert I'm looking for - it doesn't crash or anything it just re-starts the loop (which is the status quo before I tried to implement this "feature").
Thanks in advance!
The issue with this code is that prompt always returns a string value. These values may or may not be able to be converted to a Number; this conversion would be performed using parseInt or parseFloat. (If the string can be converted to a numerical value, these methods return that value; otherwise, they return NaN.) However, typeof performs no interpolation—it states the type of the variable as it exists, and not any types to which it could potentially be converted. Therefore, typeof guess will always evaluate to string. To check if a string contains a numerical value, you could use the condition if (!isNaN(parseInt(guess)) or if (!isNaN(parseFloat(guess)) (note that the isNaN method must be used instead of a traditional equality check).
However, you might want to structure your checks around ensuring that the entry is a letter rather than accounting for the myriad ways in which it might not be. For instance, # and ≥ are not numbers, but they are also not letters. Similarly, if your answerArray contains only Latin letters without diacritics, you might want to disallow guesses of characters like é and ç. Thus, consider using RegEx to check if the guessed string contains an acceptable letter. As in this Stack Overflow post, you can use the following if statement to ensure that the string is one character long and is a valid letter: if (str.length === 1 && str.match(/[a-z]/)). You can refer to that post for ways of addressing more complicated character sets (e.g., non-Latin letters or those with diacritics).

Regex - checking range of numbers with constraints

In javascript I need to parse a user input. The input is of the format: number - number. This can be repeated and separated by commas.
The following are some examples:
1-10
4-10,13-17
6-10,3-8,4-12
Here is the regex I wrote for this
(\d+[-]\d+[,]?)
However, there are 2 constraints.
The first number must be less than the second number ( 4-5 is valid but 5-4 is not)
Every number must be between 1 and N (inclusive). I will specify N.
Is there a way I can enforce these constraints with regex?
While you can certainly match the format with regexes, you can't do the kind of verification you want with them. What I would recommend is something like this (in JS):
function verifyList(list) {
var matches = list.match(/\d+-\d+/g);
for (match in matches) {
var numbers = match.match(/(\d+)-(\d+)/);
if (numbers[1] >= numbers[2]) return false;
}
return true;
}

Javascript Regex for Decimal Numbers - Replace non-digits and more than one decimal point

I am trying to limit an input to a decimal number. I'd like any invalid characters not to be displayed at all (not displayed and then removed). I already have this implemented but for whole integers (like input for a phone number) but now I need to apply it for decimal input.
Sample input/output:
default value 25.00 -> type 2b5.00 -> display 25.00
default value 265.50 -> type 2.65.50 -> display 265.50 (as if prevented decimal point from being entered)
default value 265.52 -> type 265.52. -> display 265.52 (same as previous one)
End New Edit
I found many threads that dealt with "decimal input" issue but almost 99% of them deal only with "match"ing and "test"ing the input while my need is to replace the invalid characters.
Other than trying many regexes like /^\d+(\.\d{0,2})?$/, I also tried something like the below which keeps only the first occurrence in the input. This still isn't my requirement because I need the "original" decimal point to remain not the first one in the new input. This was the code for it:
[this.value.slice(0, decimalpoint), '.', this.value.slice(decimalpoint)].join('')
This thread is the closest to what I need but since there was no response to the last comment about preventing multiple decimal points (which is my requirement), it wasn't useful.
Any help would be appreciated.
Outline: find the first ., split there and clean the parts, else just return cleaned value.
function clean(string) {
return string.replace(/[^0-9]/g, "");
}
var value = "a10.10.0";
var pos = value.indexOf(".");
var result;
if (pos !== -1) {
var part1 = value.substr(0, pos);
var part2 = value.substr(pos + 1);
result = clean(part1) + "." + clean(part2);
} else {
result = clean(value);
}
console.log(result); // "10.100"

Check string for integer

I want to validate a input field. The user should type in a phone number with minimum length of 10 digits.
So I need to check for illegal chars. It would be nice just to check wheather the input is an integer or not.
I came up with this but it does not work (n would be the string).
function isInt(n){
return typeof n== 'number' && n%1==0;
}
Any ideas?
You can do a test like this:
input.length >= 10 && /^[0-9]+$/.test(input)
That will fail if there are non-digits in the string or the string is less than 10 chars long
This should work((input - 0) automatically tries to convert the value to a number):
function isInt(input){
return ((input - 0) == input && input % 1==0);
}
There is already an SO-question about this issue: Validate decimal numbers in JavaScript - IsNumeric()
Might be an overkill for you, but Google has not too long ago announced a library for phone validation. Java and Javascript variants are available.
Validating a phone number is a little more complicated than checking if the input is an integer. As an example phone numbers can and do begin with zeros so it isn't technically and int. Also users may enter dashes: For example:
00 34 922-123-456
So, as for validating it you have a couple of options:
Use regex expression to validate, have a look at:
http://regexlib.com/
this site will have hundreds of examples
Use looping to check each characters in turn, i.e. is character int or dash
I would recommend the former as the latter depends on consistent input from users and you aren't going to get that
Why not use:
return (+val === ~~val && null !== val);
as a return in your function?
this is the output of the javascript console
> +"foobar" === ~~"foobar"
false
> +1.6 === ~~1.6
false
> +'-1' === ~~'-1'
true
> +'-1.56' === ~~'-1.56'
false
> +1 === ~~1
true
> +-1 === ~~-1
true
> +null === ~~null // this is why we need the "&& null !== val" in our return call
true

How to validate for Values "0" or "00" or "000" for textfield which has the regex and some accepted values

var myregex = /^[0-9][0-9]{0,3}$|^[0-9][0-9]{0,3}[\.][0-9]$/;
if(!myregex.test($('#txt1').val()) || $('#txt1').val()=="0"){
alert("Please Enter Correct value");
}
Now My mandatory things are it should
follow Regex
we should not able to enter the value "0" or "00" or "000"
So my above if() raises an alert if the user enter a "0" and if we enter "00" or "000" or "0000" it doesnot catch it .But if we enter "00000" it catches it due to regex. How can i handle for 2,3,4 zeros .Now Here I can put a regex which doesnot accept zeros such as this one "/^[^0].*$/" but My textfield should Accepts this values as right (0.2,0.3,0.4) .so i cannot use this regex.
Avoid regex, it's a nightmare to get exactly right, and to maintain in the future. Instead, use built-in JS string parsing functionality:
var val = parseFloat($('#txt1').val());
if (isNaN(val) || (val === 0))
{
alert("Please Enter Correct value");
}
/^[1-9]\d{0,3}(?:\.\d)?$|^0\.[1-9]$/
The first alternative matches any number from 1.0 to 9999.9. The first digit has to be at least 1, which eliminates leading zeroes. The fraction part is optional ((?:\.\d)?), so it also matches integers from 1 to 9999. The second alternative handles the special cases of 0.1 through 0.9.
It looks like your regular expression requires 0 through 9999, or 0.0 through 9999.9, but you do not want to accept a 0 alone, or a series of zeros.
If that's the case, I'd say use something similar to ken's answer and process it as a float, then check that the float is above 0 and below 9999.9:
var val = parseFloat($("#txt1").val());
if(isNan(val) || val <= 0 || val > 9999.9) {
alert("Please enter a value between 0 and 9999.9");
}
If you need to use your regex and just add a check that the string doesn't consist entirely of zeroes, you can add a negative lookahead expression: (?!0+$) and enclose the alternation in a non-capturing group:
/^(?!0+$)(?:[0-9][0-9]{0,3}|[0-9][0-9]{0,3}[\.][0-9])$/
No need for Regex or any of that, quite simple.
if(('#txt1').val() < 0.1 ){
alert("Please Enter Correct value");
}
There you go, problem solved

Categories

Resources