Suppose I have a string containing "hello, world!" and another one with "hello world", I want my function to return false for the first and trye for the second, by basically checking it against an array of valid characters, for example a-z.
Problems is I do NOT want to use a regex. I could use .indexOf but it only works for ONE character.
Any way to do this, possibly in a non-blocking way (using node.js)?
Thanks in advance.
In PHP, I used to do something similar:
$sUser = 'my_username01';
$aValid = array('-', '_');
if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
echo 'Your username is not properly formatted.';
}
function hasBadChars(s) {
var badChars = ['!'],
i;
for (i = 0; i < s.length; ++i) {
if (badChars.indexOf(s[i])) {
return true;
}
}
return false;
}
console.log(hasBadChars('Hello world!'));
Related
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()" />
I have written a function that I want to take in a string and then return a string that contains only the number characters from the original string. It
function pureNumbers() {
var result;
for (var i = 0; i < phoneNumber.length; i++) {
if (Number(phoneNumber[i]) !== NaN) {
result ? result = result + phoneNumber[i] : result = phoneNumber[i]
}
}
return result;
}
pureNumbers('(123) 456-7890')
Desired result:
result: '1234567890'
What I actually get is:
result: 'undefined(123) 456-7890'
I know there's two issues here (possibly more).
The undefined at the beginning of my result is because my function is attempting to return the value of result in the first loop's iteration, before anything has been assigned to it. I set up the ternary conditional to cover this, not sure why it's not working...
My first if() conditional is intended to make the given character of the string be added to result only if it is a number, yet every single character is being added.
Any help appreciated - thanks in advance.
This gets all the numbers from a string as an array, then .join("") to join together the strings with no delimiter between them, I.e., a consecutive concatenation string of digit matches.
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern ).join("");
Yields "1021948948"
The basic logic is below:
var x = 'Hello please call (727) 902-1112';
var numbers = x.match(/[0-9]/g).join('');
console.log(numbers);
Result: 7279021112
Now as to a function, I think this might help you:
var x = 'Hello please call';
var y = 'Hello please call (727) 902-1112';
function pureNumbers(param) {
result = param.match(/[0-9]/g);
if (Array.isArray(result)) {
return result.join('');
}
return false;
}
console.log(pureNumbers(x)); // returns false
console.log(pureNumbers(y)); // returns 7279021112
Note: isArray() does not work in older versions of IE 9. You would have to do it differently.
Your can also try the following: string.replace(/[^0-9]/g, ''); OR string.replace(/\D/g,''); to strip all the non-digit characters.
function pureNumbers(str) {
var num = str.replace(/[^0-9]/g, '');
return num;
}
alert(pureNumbers('(123) 456-7890'));
I only changed your function a little bit, though it can be solved in many ways, especially with regex.
function pureNumbers(phoneNumber) {
var result = "";
for (var i = 0; i < phoneNumber.length; i++) {
if (!isNaN(phoneNumber[i]) && phoneNumber[i].trim() !== '') {
result += phoneNumber[i];
}
}
return result;
}
Hope you may get some hint and improve for better solution.
I've looked high and low for this, with no real idea how to do it now... my scenario:
var strArray = ['Email Address'];
function searchStringInArray(str, strArray) {
for (var j = 0; j < strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
var match = searchStringInArray('Email', strArray);
Email does NOT equal Email Address... however .match() seems to match the two up, when it shouldn't. I want it to match the exact string. Anyone have any idea how I do this?
You already have .indexOf() for the same thing you are trying to do.
So rather than looping over, why not use:
var match = strArray.indexOf('Email');
String.match is treating your parameter 'Email' as if it is a regular expression. Just use == instead:
if (strArray[j] == str) return j;
From the Mozilla Development Network page on String.match:
If a non-RegExp object obj is passed, it is implicitly converted to a
RegExp by using new RegExp(obj)
Alternatively using RegExp
Use ^ and $
var str = "Email";
new RegExp(str).test("Email address")
Result: true
And for this:
var str = "Email";
new RegExp("^" + str + "$").test("Email address")
Result: false
Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox
How can I quickly validate if a string is alphabetic only, e.g
var str = "!";
alert(isLetter(str)); // false
var str = "a";
alert(isLetter(str)); // true
Edit : I would like to add parenthesis i.e () to an exception, so
var str = "(";
or
var str = ")";
should also return true.
Regular expression to require at least one letter, or paren, and only allow letters and paren:
function isAlphaOrParen(str) {
return /^[a-zA-Z()]+$/.test(str);
}
Modify the regexp as needed:
/^[a-zA-Z()]*$/ - also returns true for an empty string
/^[a-zA-Z()]$/ - only returns true for single characters.
/^[a-zA-Z() ]+$/ - also allows spaces
Here you go:
function isLetter(s)
{
return s.match("^[a-zA-Z\(\)]+$");
}
If memory serves this should work in javascript:
function containsOnlyLettersOrParenthesis(str)
(
return str.match(/^([a-z\(\)]+)$/i);
)
You could use Regular Expressions...
functions isLetter(str) {
return str.match("^[a-zA-Z()]+$");
}
Oops... my bad... this is wrong... it should be
functions isLetter(str) {
return "^[a-zA-Z()]+$".test(str);
}
As the other answer says... sorry