It consists of a string of 7 numeric digits. The string is preceded by two or three characters and ends with a single character. There should be no character space within the entire string
function Country(country) {
var message = document.getElementsByClassName("error-message");
var letters = /^\d{7}?$/;
if ( country =="" || country.match(letters)) {
text="";
message[4].innerHTML = text;
return true;
}
else {
text="Country name should contain only letters";
message[4].innerHTML = text;
return false;
}
}
Try following regex to become a string with two or three alphabetic letters at the begin, in the middle three numbers and at the end one alphabetic letter!
^[a-zA-Z]{2,3}[0-9]{3}[a-zA-Z]{1}$
It consists of a string of 7 numeric digits.
var isSeven = country.length===7;
The string is preceded by
two or three characters and ends with a single character.
var isCountry = /^[a-z]{2,3}\d+[a-z]{1}$/i;
if we combine the two conditions we reach the pattern:
digits deponds on letters
Numbers of letters Three, therefore Numbers of digits Three like you suggest in comment 'abc789a'.
Numbers of letters Two,consequently Numbers of digits Four 'ab6789a'.
There should be no character space within the entire string.
var hasNoSpace = /[^\s]/g;
finally
return isCountry.test(country) && isSeven && hasNoSpace.test(country)
Related
How do I write a regular expression for use in JavaScript that'll ensure the first and last characters of a string are always digits?
r = /\D+/g;
var s = "l10ddd31ddd5705ddd";
var o = r.test(s);
console.log(o);
So, 1KJ25LP3665 would return true, while K12M25XC5750 would return false.
You can have a regex like below:
/^\d(.*\d)?$/
The ^ to begin match from start of the string and $ to continue match till end of the string.
\d to match a digit at the beginning and the end.
.* to match zero or more characters in between.
We make the group 1 => (.*\d) optional with the ? metacharacter to optionally match zero or more characters ending with the digit till the end of the string. This would help if the string has only a single digit.
if(s.matches("\\d.*\\d"))
{
// Do what you want once both start and ending characters are digits
}
This solution achieves the same result without a Regex. It also takes care of empty strings or strings with only one character.
function startsAndEndsWithDigits(string)
{
if(string.length>0)//if string is not empty
{
var firstChar = string.split('')[0];//get the first charcter of the string
var lastChar = string.split('')[string.length -1];//get the last charcter of the string
if(firstChar.length>0 && lastChar.length>0)
{ //if first and last charcters are numbers, return true. Otherwise return false.
return !isNaN(firstChar) && !isNaN(lastChar);
}
}
return false;
}
Usage example:
startsAndEndsWithDigits('1KJ25LP3665'); //returns true
startsAndEndsWithDigits('K12M25XC5750');//returns false
startsAndEndsWithDigits(''); //returns false
startsAndEndsWithDigits('a'); //returns false
startsAndEndsWithDigits('7'); //returns true
I am still new to javascript and I am trying to validate my form.
One of my inputs is a text input for an identity number that follows the following pattern: ####XX where # represents a number and X represents a capital letter from A-Z.
Here is my code so far:
var IDnum = document.getElementById('identityNumber').value;
if ( (isNaN(IDnum.charAt(0))) && (isNaN(IDnum.charAt(1)))&& (isNaN(IDnum.charAt(2))) && (isNaN(IDnum.charAt(3))) && (!isNaN(IDnum.charAt(4))) )
{
document.getElementById('identityError').style.display = "inline-block";
}
else
{
document.getElementById('identityError').style.display = "none";
}
I have tried to google it and have seen some info where they use a RegExp however i have yet to learn anything like that.
With my code above, no matter what i type it, it still validates it. Any ideas what i am doing wrong and if there is a more simple and easier way?
EDIT: after looking to regex and similar answers the following
^\d{4}[A-Z]{2}$
did not work either
A regular expression is the way to go here. Use the pattern ^\d{4}[A-Z]$:
document.querySelector('button').addEventListener('click', (e) => {
const { value } = document.querySelector('input');
if (value.match(/^\d{4}[A-Z]$/)) {
console.log('OK');
} else {
console.log('Bad');
}
});
<input>
<button>submit</button>
^\d{4}[A-Z]$ means:
^ - Match the start of the string
\d{4} - Match a digit character (0 to 9) 4 times
[A-Z] - Match a character from A to Z
$ - Match the end of the string
You can use regular expression to identify whether string has 4 digits before a character.
each \d represents a digit, \d\d\d\d means 4 digits (alternatively \d{4}).
followed by . means 4 digits followed by any character.
function isAllowed(str) {
return str.match(/^\d\d\d\d.$/g) !== null
}
console.log(isAllowed("1234X"));
console.log(isAllowed("123a"));
console.log(isAllowed("3892#"));
console.log(isAllowed("X"));
var IDnum = document.getElementById('identityNumber').value;
if (isAllowed(IDnum))
{
document.getElementById('identityError').style.display = "inline-block";
}
else
{
document.getElementById('identityError').style.display = "none";
}
function RegexCheck(str) {
var pettern = new RegExp('^[0-9]{4,}[A-Z]{1,}');
return pettern.test(str);
}
console.log(RegexCheck("####X"));
console.log(RegexCheck("1234A"));
console.log(RegexCheck("2C35B"));
console.log(RegexCheck("A698C"));
console.log(RegexCheck("1698b"));
You can use the pattern attribute to provide a RegExp string:
^\d{4}[A-Z]{2}$ would be a string consisting of 4 digits followed by two capital letters between A and Z.
Explanation
^: Beginning of the string.
\d{4}: Exactly 4 digits in a row (this could also be written as \d\d\d\d)
[A-Z]{2}: Exactly 2 characters from the range of character between A and Z (alternatively [A-Z][A-Z]).
$: The end of the string.
input:invalid {
color: red;
}
input:not(:invalid) {
color: green;
}
<input type="text" pattern="^\d{4}[A-Z]{2}$">
I have a text file which has strings separated by whitespace. The text file contains some special characters (latin, currency, punctuations etc.) Which need to be discarded from final output. Please note that legal characters are all characters in Unicode except these special characters.
We need to separate/split text by whitespaces and then remove only leading and trailing special characters. If special characters are in between two legal characters then we won't remove them.
I can easily do it in two phases. Split text by whitespaces and then remove only leading and trailing special characters from each string. However, I need to process string only once. Is there any way, it could be achieved in one pass. Note: We can't use RegEx.
For this question assume that these characters are special:
[: , ! . < ; ' " > [ ] { } ` ~ = + - ? / ]
Example:
:!/,.<;:.?;,BBM!/,.<;:.?;,` IS TALKING TO `B!?AM!/,.<;:.?;,
Here output would be an array of valid strings: ["BBM", "IS", "TALKING", "TO", "B!?AM"]
Make simple state machine (finite automata)
Walk in a loop through all chars
At every step check if current char is letter, space or special
Execute some operation (perhaps empty) depending on state and char kind
Change state if needed
for example, you may stay in "special" state until letter is met. Remember starting index of the word and make state "inside word". Continue until special char or space is met (it is still not clear from your question).
I have used typescript and have done it in a single pass.
Please note that isSpecialCharacterCode(charCode) function simply checks whether unicode of text character is same as unicode of provided special characters.Same is true for isWhitespaceCode(charCode) function.
parseText(text: string): string[]{
let words : string[] = [];
let word = "";
let charCode = 1;
let haveSeenLegalChar = false; //set it if we have encountered legal character in text
let seenSpecialCharsToInclude = false; //set it if we have encountered //special character in text
let inBetweenSpecialChars = ""; // string containing special chars //which may be included in between legal word
for(let index = 0; index < text.length; index++){
charCode = text.charCodeAt(index);
let isSpecialChar = isSpecialCharacterCode(charCode);
let isWhitespace = isWhitespaceCode(charCode);
if(isSpecialChar && !isWhitespace){
//if this is a special character then two cases
//first is: It can be part of word (it is only possible if we have already seen atleast one legal character)
//Since it can be part of word but we are not sure whether this will be part of word so store it for now
//second is: This is either leading or trailing special character..we should not include these in word
if(haveSeenLegalChar){
inBetweenSpecialChars += text[index];
seenSpecialCharsToInclude = true;
}else{
//since we have not seen any legal character till now so it must be either leading or trailing special chars
seenSpecialCharsToInclude = false;
inBetweenSpecialChars = "";
}
}else if(isWhitespace){
//we have encountered a whitespace.This is either beginning of word or ending of word.
//if we have encountered any leagl char, push word into array
if(haveSeenLegalChar){
words.push(word);
word = "";
inBetweenSpecialChars = "";
}
haveSeenLegalChar = false;
}else if(!isSpecialChar){
//legal character case
haveSeenLegalChar = true;
if(seenSpecialCharsToInclude){
word += inBetweenSpecialChars;
seenSpecialCharsToInclude = false;
inBetweenSpecialChars = "";
}
word += text[index];
}
}
return words;
}
I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");
My account must have number and letters.And its length range 4 and 8.
It's not only number and it's not only letters.
Right ex: a111 ,1a1bb, aa111a, 111aaa. Error ex: abcdef, 12345, a123!.
How can I write the Regular Expression.
I tried write that:([a-z]+[0-9]+[a-z]*){4,10}|([0-9]+[a-z]+[0-9]*){4,10}.
But it's not match. Where is my error?
Try this: update ^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{4,20})$
Here
^(
(?=.*\d) // must contains one digit from 0-9
(?=.*[a-zA-Z]) //must contains one lowercase Uppercase characters
[a-zA-Z0-9] //match any letter or number previous condition checking
{4,20} //length at least 4 characters and maximum of 20
)$
Live demo
Try this:
/^(?=.[a-z]+[0-9]|[0-9]+[a-z].)[a-zA-Z\d*]{4,8}$/
var filter = /^(?=.*[a-z]+[0-9]|[0-9]+[a-z].*)[a-zA-Z\d*]{4,8}$/;
var vals = "11aa11";
if (filter.test(vals)){
alert('working');
}else {
alert('not working');
}
Try this
var patt = new RegExp("(([A-Za-z][0-9]) |([0-9][A-Za-z])) ([A-Za-z]*[0-9]*){2,6}");
var res = patt.exec(test_str);