I am writing some javascript to validate user input in a text area. Here are the requirements for input format:
Input must be in the format of two hex values separated by a space (i.e. A7 B3 9D).
Input must be valid hex values.
I have requirement #2 sorted out with a regExpression valueOne.match("[0-9A-Fa-f]{1}") (or at least I hope that is the recommended way to do it). So I am just looking for some input on how to go about handling requirement number one in a simple and efficient way.
Thanks!
This regex will do it:
/^[0-9A-F]{2}(\s[0-9A-F]{2})*$/i
That is:
^ // beginning of string
[0-9A-F]{2} // two characters of 0-9 or A-F
(\s[0-9A-F]{2})* // zero or more instances of a space followed by
// two characters of 0-9 or A-F
$ // end of string
Where the i flag at the end makes it case insensitive.
To use it:
var valueOne = // set to your textarea's value here
if (/^[0-9A-F]{2}(\s[0-9A-F]{2})*$/i.test(valueOne)) {
// is OK, do something
} else {
// is not OK, do something
}
Related
I need to validate range R1:C1-R2:C2 range
I tried with,
function isValid(rc) {
if (rc)
if (rc.trim() === "") return false;
var isPattern = /^[0-9]+:[0-9]+-[0-9]+:[0-9]+$/.test(rc);
if (!isPattern) return false;
return ((rc));
}
But the above code also takes 9:9-0:0 or 0:0-0:0
UPDATE:
How do I check whether the given range after a numeric validation at client side is correct in the server side. Because, at server side range may be invalid.
You need to check that there are some alphabetic characters, then numeric characters - this is how to match a field: [a-z]+\d+. It will match some characters, then some numbers. E.g. a1, ASD34. It won't match 12 or sab though.
If you put all together, you get this regex:
/^[a-z]+\d+:[a-z]+\d+\s*-\s*[a-z]+\d+:[a-z]+[0-9]+$/i
Explanation:
/../i matches case insensitively, so it's enough to specify [a-z], no need to type [a-zA-Z]
this matches a field: [a-z]+\d+, like R1 or B12. It won't match 12 or AB
\s*-\s* tolerates spaces around the dash
so we got: field:field-field:field and that's what you want.
You can play with this regex demo.
Checking if the values are actually okay, it takes more than a regex. You'll have to split the code by the dash and the colons and compare the values.
I'm writing an application that requires color manipulation, and I want to know when the user has entered a valid hex value. This includes both '#ffffff' and '#fff', but not the ones in between, like 4 or 5 Fs. My question is, can I write a regex that determines if a character is present a set amount of times or another exact amount of times?
What I tried was mutating the:
/#(\d|\w){3}{6}/
Regular expression to this:
/#(\d|\w){3|6}/
Obviously this didn't work. I realize I could write:
/(#(\d|\w){3})|(#(\d|\w){6})/
However I'm hoping for something that looks better.
The shortest I could come up with:
/#([\da-f]{3}){1,2}/i
I.e. # followed by one or two groups of three hexadecimal digits.
You can use this regex:
/#[a-f\d]{3}(?:[a-f\d]{3})?\b/i
This will allow #<3 hex-digits> or #<6 hex-digits> inputs. \b in the end is for word boundary.
RegEx Demo
I had to find a pattern for this myself today but I also needed to include the extra flag for transparency (i.e. #FFF5 / #FFFFFF55). Which made things a little more complicated as the valid combinations goes up a little.
In case it's of any use, here's what I came up with:
var inputs = [
"#12", // Invalid
"#123", // Valid
"#1234", // Valid
"#12345", // Invalid
"#123456", // Valid
"#1234567", // Invalid
"#12345678", // Valid
"#123456789" // Invalid
];
var regex = /(^\#(([\da-f]){3}){1,2}$)|(^\#(([\da-f]){4}){1,2}$)/i;
inputs.forEach((itm, ind, arr) => console.log(itm, (regex.test(itm) ? "valid" : "-")));
Which should return:
#123 valid
#1234 valid
#12345 -
#123456 valid
#1234567 -
#12345678 valid
#123456789 -
I have an input for a phone number in french format
The input accepts two kinds of format, so i can input this:
0699999999
+33699999999
no check is done for the length of the number.
The table in database, the field is of varchar 12, i can have shorter input though.
The constraints: input contains only digits from 0 to 9, optional '+' sign accepted only if it starts the string, not after.
Currently i am in Angular with a directive, in that directive the heart is this expression :
var transformedInput = inputValue.replace(/[^0-9]/g, '');
i want the optional leading '+' sign, how can i achieve this?
thanks.
You could make the plus sign optional:
if (/\+?\d*/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
subject is the text you want to check. \+ makes the plus sign a literal and the questionmark makes it optional.
If you just want to check wether ther is a plussign drop the questionmark. But if that is your goal don't use a regex. That is too much overhead. Simply get the first charactor of the trimmed string and check for the plus.
Change it to
var transformedInput = inputValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1');
Note - this will NOT add a + unless there is already a + in the input
What it does is
Do not remove the + symbol on the first replace
Remove every + symbol that is preceded by some character on the 2nd replace
I'm using the following code to negate the characters in the regexp. By checking the inverse, I can determine if the value entered is correctly formatted. Essentially, any digit can be allowed but only one decimal point (placed anywhere in the string.) The way I have it now, it catches all numerals, but allows for multiple decimal points (creating invalid floats.) How can I adjust this to catch more than one decimal points (since I only want to allow for one)?
var regex = new RegExp(/[^0-9\.]/g);
var containsNonNumeric = this.value.match(regex);
if(containsNonNumeric){
this.value = this.value.replace(regex,'');
return false;
}
Here is what I'm expecting to happen:
First, valid input would be any number of numerals with the possibility of only one decimal point. The current behavior: The user enters characters one by one, if they are valid characters they will show up. If the character is invalid (e.g. the letter A) the field will replace that character with ''(essentially behaving like a backspace immediately after filling the character in. What I need is the same behavior for the addition of one too many decimal points.
As I understand your question the code below might be what you are looking for:
var validatedStr=str.replace(/[^0-9.]|\.(?=.*\.)/g, "");
It replaces all characters other then numbers and dot (.), then it replaces all dots followed by any number of 0-9 characters followed by dot.
EDIT based on first comment - the solution above erases all dots but the last, the author wants to erase all but the first one:
Since JS does not support "look behind", the solution might be to reverse string before regex, then reverse it again or to use this regex:
var counter=0;
var validatedStr=str.replace(/[^0-9.]|\./g, function($0){
if( $0 == "." && !(counter++) ) // dot found and counter is not incremented
return "."; // that means we met first dot and we want to keep it
return ""; // if we find anything else, let's erase it
});
JFTR: counter++ only executes if the first part of condition is true, so it works even for strings beginning with letters
Building upon the original regex from #Jan Legner with a pair of string reversals to work around the look behind behavior. Succeeds at keeping the first decimal point.
Modified with an attempt to cover negatives as well. Can't handle negative signs that are out of place and special cases that should logically return zero.
let keep_first_decimal = function(s) {
return s.toString().split('').reverse().join('').replace(/[^-?0-9.]|\.(?=.*\.)/g, '').split('').reverse().join('') * 1;
};
//filters as expected
console.log(keep_first_decimal("123.45.67"));
console.log(keep_first_decimal(123));
console.log(keep_first_decimal(123.45));
console.log(keep_first_decimal("123"));
console.log(keep_first_decimal("123.45"));
console.log(keep_first_decimal("a1b2c3d.e4f5g"));
console.log(keep_first_decimal("0.123"));
console.log(keep_first_decimal(".123"));
console.log(keep_first_decimal("0.123.45"));
console.log(keep_first_decimal("123."));
console.log(keep_first_decimal("123.0"));
console.log(keep_first_decimal("-123"));
console.log(keep_first_decimal("-123.45.67"));
console.log(keep_first_decimal("a-b123.45.67"));
console.log(keep_first_decimal("-ab123"));
console.log(keep_first_decimal(""));
//NaN, should return zero?
console.log(keep_first_decimal("."));
console.log(keep_first_decimal("-"));
//NaN, can't handle minus sign after first character
console.log(keep_first_decimal("-123.-45.67"));
console.log(keep_first_decimal("123.-45.67"));
console.log(keep_first_decimal("--123"));
console.log(keep_first_decimal("-a-b123"));
Without using jQuery, what is the best way to limit text entry of a textbox to numbers, lowercase letters and a given set of symbols (for example - and _)? If the user enters an uppercase letter, I would like it to be automatically converted to a lowercase letter, and if the user enters a symbol not within the given set, I would like to be able to instantly show a validation error (show some element adjacent to or below the text box).
What's the cleanest cross-browser way of doing this without the aid of jQuery?
Attach the following to your elements onkeyup event.
function onkeyup()
{
var el = document.getElementById("id"); // or however you want to get it
el.value = el.value.toLowerCase(); // covert to lower case
if (el.value.match(/[^-\d\w]/)) // check for illegal characters
{
// show validation error
...
// remove invalid characters
el.value = el.value.replace(/[^-\d\w]/g, "");
}
else
{
// hide validation error
}
}
The regex matches any character which is not a digit, a letter, a hyphen or an underscore.