javascript validation for special character's index/position - javascript

I have input as 23 digit key from input box which will be separated by '-'.
E.g: XXXXX-XXXXX-XXXXX-XXXXX
This is expected format means, 5 digit followed by -(hyphen).
Problem:
User can input any data/wrong format, like XXX-XXXXX-XXXXX-XXXXXXX, in this case index of hyphen is invalid. How can I valided the index of hyphen?
I tried:
if((prd_len==23) && (n!=-1))
{
var indices = [];
for(var i=0; i<prd_id.length;i++)
{
if (prd_id[i] === "-")
{
indices.push(i);
}
}
for(var x=0;x<indices.length;x++)
{
if((indices[x]!=5) || (indices[x]!=11) || (indices[x]!=17))
{
$('#msgErr1').text('Please enter valid key.');
flag=1;
}
}
}
where prd_len=length of the accepted input from user.

Try regular expressions
if(input.match(/^(\d{5}-){3}\d{5}$/))
everything is OK
This expression basically reads "five digits and a dash - three times, then five digits". For further reference see
http://www.regular-expressions.info/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

As thg435 said, but more human-readable :-)
var correct = input.match(/^\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d$)

Related

checking if a string follows a given pattern in javascript

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}$">

Javascript how can I find character "utf-16" at string

Have a question. Sorry for my English.
I have a string. Customer enter SMS text at text-area.
How can I find the existing character of utf-16 at the string or not?
At php I check this code:
if (iconv("UTF-8","UTF-8//IGNORE",$_entry_text) != $_entry_text) {
// exist utf-16
}
How can I at Javascript check? Try to find an answer the second day ((
Thanks.
A string is a series of characters, each which have a character code. ASCII defines characters from 0 to 127, so if a character in the string has a code greater than that, then it is a Unicode character. This function checks for that. See String#charCodeAt.
function hasUnicode (str) {
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 127)
return true;
}
return false;
}
Then use it like, hasUnicode("Test message");
If it's a short string, one method would be to just look across the length of it and check if any of the char-codes sit outside of the single-byte 0-255 range
if (_entry_text.charCodeAt(i) > 255) ...
I think there is no need for a loop;
var ascii = /^[ -~]+$/;
ascii.test("Sefa"); // it is true no non-ascii characters
ascii.test("Sefa£"); // it is false there is non-ascii character

javascript indexof regex A-Za-z0-9 always returns false

I have created a JS fiddle https://jsfiddle.net/95r110s9/#&togetherjs=Emdw6ORNpc
HTML
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
JS
validateinputentries(){
landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
goodcharacters = "/^[a-zA-Z0-9#.,;:'\s]+$/gi";
for (var i = 0; i < landlordstreetaddress2.length; i++){
if (goodcharacters.indexOf(landlordstreetaddress2.charAt(i)) != -1){
console.log('Character is valid');
}
}
}
Its pulling the value from an input and running an indexOf regex expression with A-Z a-z and 0-9 with a few additional characters as well.
The problem is that it works with the entry of BCDEFG...etc and 12345...etc, but when I type "A" or "Z" or "0" or "1", it returns incorrectly.
I need it to return the same with 0123456789, ABCDEF...XYZ and abcdef...xyz
I should point out that the below does work as intended:
var badcharacters = "*|,\":<>[]`\';#?=+/\\";
badcharacter = false;
//firstname
for (var i = 0; i < landlordfirstname.value.length; i++){
if (badcharacters.indexOf(landlordfirstname.value.charAt(i)) != -1){
badcharacter = true;
break;
}
if(landlordfirstname.value.charAt(0) == " "){
badcharacter = true;
break;
}
}
String.prototype.indexOf()
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.
So, you're trying to search this value "/^[a-zA-Z0-9#.,;:'\s]+$/gi" which "never" will be found in the entered string.
You actually want to test that regexp against the entered value.
/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)
function validateinputentries() {
var landlordstreetaddress2 = document.getElementById('landlordstreetaddress2').value;
if (/^[a-zA-Z0-9#.,;:'\s]+$/gi.test(landlordstreetaddress2)) {
console.log('Characters are valid');
} else {
console.log('Characters are invalid');
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
You're trying to combine two different methods of testing a string -- one way is with a regex; the other way is by checking each character against a list of allowed characters. What you've wound up with is checking each character against a list of what would have been a regex, if you hadn't declared it as a string.
Those methods conflict with each other; you need to pick one or the other.
Check each character:
This is closest to what you were attempting. You can't use character ranges here (like a-zA-Z) as you would in a regex; you have to spell out each allowed character individually:
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var goodcharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#.,;:' ";
var badcharactersfound = false;
for (var i = 0; i < address.length; i++) {
if (goodcharacters.indexOf(address.charAt(i)) == -1) {
badcharactersfound = true;
console.log("not allowed: ", address.charAt(i));
}
}
if (badcharactersfound) {
// Show validation error here
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />
Regular Expressions
The regex version is much simpler, because the regular expression is doing most of the work. You don't need to step through the string, just test the whole string against the regex and see what comes out. In this case you're looking to see if the input contains any characters that aren't allowed, so you want to use the character exception rule: [^abc] will match any character that is not a, b, or c. You don't want to anchor the match to the beginning or the end of the string, as you were doing with the initial ^ and the trailing $; and you can leave out the + because you don't care if there are sequential bad characters, you just care if they exist at all.
var validateinputentries = function() {
var address = document.getElementById('landlordstreetaddress2').value;
var regex = new RegExp("[^a-zA-Z0-9#.,;:'\\s]","g")
var badcharactersfound = address.match(regex);
// or the above two lines could also have been written like this:
// var bad = address.match(/[^a-zA-Z0-9#.,;:'\s]/g)
// In either case the "g" operator could be omitted; then it would only return the first bad character.
if (badcharactersfound) {
console.log("Not allowed: ", badcharactersfound);
}
}
<input id="landlordstreetaddress2" class="landlordinputs" onfocusout="validateinputentries()" />

validate input value contain x numbers of numeric characters

I need to validate a input field which should contain at least x number of numeric characters.
eg: let say I need to input value has at least 5 numeric characters
12345 - valid
AB12345 - valid
123456 - valid
AB312312 - valid
asd - not valid
213 - not valid
First I tried with input.length, but I don't know it will have a leading letters or not, so length doesn't help for me
how should I do this validation with jquery or javascript ?
Let say you are looking at validating 5 numeric then you can use regular expression /(?=(?:[\d]){5}).
What this expression does is that;
(?=) means start looking ahead
(?:[\d]) means match digits but don't capture them
{5} means (?:[\d]) (match digit) do 5 times
"use strict";
let numbers = [ '12345', 'ABC12345', '123456', 'AB312312', 'asd', '213'];
numbers.forEach(number=> {
if (/(?=(?:[\d]){5})/.exec(number)) {
console.log(number + " is valid.");
};
});
Using regular expressions will do the trick
function check(str,x){
var pattern = '^[a-zA-Z0-9]*[0-9]{'+x+'}[a-zA-Z0-9]*$';
if(str.match(pattern)) return true;
return false;
}
How about something like this
x = 5;
myString = "AB12345";
if (myString.replace(/[^0-9]/g,"").length >= x) {
alert('valid');
} else {
alert('not valid');
}
see this jsfiddle.
If
inputValue.replace(/[^0-9]/g,"").length < 5
then input field is invalid.

replace non matches between delimiters

I've have a input string:
12345,3244,654,ffgv,87676,988ff,87657
I'm having a difficulty to transform all terms in the string that are not five digit numbers to a constant 34567 using regular expressions. So, the output would be like this:
12345,34567,34567,34567,87676,34567,87657
For this, I looked at two options:
negated character class: Not useful because it does not execute directly on this expression ,[^\d{5}],
lookahead and lookbehind: Issue here is that it doesn't include non-matched part in the result of this expression ,(?!\d{5}) or (?<!\d{5}), for the purpose of substitution/replace.
Once the desired expression is found, it would give a result so that one can replace non-matched part using tagged regions like \1, \2.
Is there any mechanism in regular expression tools to achieve the output as mentioned in the above example?
Edit: I really appreciate those who have answered non-regex solutions, but I would be more thankful if you provide a regex-based solution.
You don't need regex for this. You can use str.split to split the string at commas first and then for each item check if its length is greater than or equal to 5 and it contains only digits(using str.isdigit). Lastly combine all the items using str.join.
>>> s = '12345,3244,654,ffgv,87676,988ff,87657'
>>> ','.join(x if len(x) >= 5 and x.isdigit() else '34567' for x in s.split(','))
'12345,34567,34567,34567,87676,34567,87657'
Javascript version:
function isdigit(s){
for(var i=0; i <s.length; i++){
if(!(s[i] >= '0' && s[i] <= '9')){
return false;
}
}
return true;
}
arr = "12345,3244,654,ffgv,87676,988ff,87657".split(",");
for(var i=0; i < arr.length; i++){
if(arr[i].length < 5 || ! isdigit(arr[i])) arr[i] = '34567';
}
output = arr.join(",")
Try the following: /\b(?!\d{5})[^,]+\b/g
It constrains the expression between word boundaries (\b),
Followed by a negative look-ahead for non five digit numbers (!\d{5}),
Followed by any characters between ,
const expression = /\b(?!\d{5})[^,]+\b/g;
const input = '12345,3244,654,ffgv,87676,988ff,87657';
const expectedOutput = '12345,34567,34567,34567,87676,34567,87657';
const output = input.replace(expression, '34567');
console.log(output === expectedOutput, expectedOutput, output);
This approach uses /\b(\d{5})|(\w+)\b/g:
we match on boundaries (\b)
our first capture group captures "good strings"
our looser capture group gets the leftovers (bad strings)
our replacer() function knows the difference
const str = '12345,3244,654,ffgv,87676,988ff,87657';
const STAND_IN = '34567';
const massageString = (str) => {
const pattern = /\b(\d{5})|(\w+)\b/g;
const replacer = (match, goodstring, badstring) => {
if (goodstring) {
return goodstring;
} else {
return STAND_IN;
}
}
const r = str.replace(pattern,replacer);
return r;
};
console.log( massageString(str) );
I think the following would work for value no longer than 5 alphanumeric characters:
(,(?!\d{5})\w{1,5})
if longer than 5 alphanumeric characters, then remove 5 in above expression:
(,(?!\d{5})\w{1,})
and you can replace using:
,34567
You can see a demo on regex101. Of course, there might be faster non-regex methods for specific languages as well (python, perl or JS)

Categories