I have a string from which I want to check if it only contains characters that are allowed.
Allowed are only the letters a, b, c, d, e, k. I thought of something like this:
var string1 = "abcdekabc"
if (string1 contains only a,b,c,d,e,k) {
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
How can I do this? Is there a regex that would help me? Unfortunately I don't have experience with regex.
Yes there is a regexp :
var pattern = new RegExp('[^abcdek]', 'i');
var string1 = "abcdekabc";
if(!pattern.test(string1)){
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
Which can be reduce to :
var string1 = "abcdekabc";
if(!(/[^abcdek]/i).test(string1)){
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
If you prefer, you can go the other way arround (not checking illegal characters) :
var string1 = "abcdekabc";
if((/^[abcdek]+$/i).test(string1)){
document.write("everything is fine");
} else {
document.write("there is one or more character that is not allowed");
}
Related
I am trying to validate a string where the first character must be an 'x' and the remaining characters must be numerical. For example:
x1234 == true;
k1234 == false;
x12k4 == false;
1x123 == false;
Here is my code:
function isValidCode(code){
var firstLetter = code.substring(0,1);
var remainingCode = code.substring(1);
var validCode = false;
// Debugging
console.log(firstLetter);
console.log(remainingCode);
if(firstLetter == 'x'){
validCode = true;
}
if(isNumeric(Number(remainingCode))){
validCode = true;
}
}
I've debugged my isNumeric() function, so I'm 99.9% sure the issue isn't there, but here it is just in case:
function isNumeric(numberIn)
{
var returnValue = true;
if (isNaN(numberIn) || isNaN(parseInt(numberIn, 10)))
{
returnValue = false;
}
return returnValue;
}
I've tried several things such as reversing my logic where I start with the given condidtion being true and then checking if(!(firstLetter == 'x')) I've tried == and ===and I've tried casting the remaining portion of the code with Number() , +() and not casting it at all, but none of these seeem to do the trick. The console does log the proper first character and remaining characters in the code so I'm not sure what is wrong.
You can use a regular expression test:
function isValidCode(code) {
return /^[a-z]\d+$/.test(code);
}
I am making an assumption that a lower case letter is required, followed by at least one digit.
To match only only the letter 'x', use:
function isValidCode(code) {
return /^x\d+$/.test(code);
}
You can use RegExp /^x(?=\d+$)/ to match x at beginning of input followed by digits followed by end of input
var arr = ["x1234"
, "k1234"
, "x12k4"
, "1x123"];
var re = /^x(?=\d+$)/;
arr.forEach(function(str) {
console.log(`${str}: ${re.test(str)}`)
})
I'm trying to work out how to check a string for a specific word, and if that word exists set a new variable
I have the following jQuery code:
val= $('#' + this_id).val();
val can contain different strings of words.
I know I can do :
if (/Approve/i.test(val)) {
msg = "Approve"
}
But this also matches, Approved.. how do I match only Approve ?
Ultimately I'm look to do :
if val contains Approve msg = "Approve"
if val contains Approved msg = "Approved"
if val contains Reject msg = "Rejected"
Thanks
You can use word boundary (\b):
if (/\bApprove\b/i.test(val)) {
msg = "Approve";
}
According to Regular expression tutorial - word boundary,
There are three different positions that qualify as word boundaries:
Before the first character in the string, if the first character is a word character.
After the last character in the string, if the last character is a word character.
Between two characters in the string, where one is a word character and the other is not a word character.
Use this.
if (/^Approve$/i.test(val)) {
var msg = "Approve"
}
^ marks the start
$ marks the end
function check(val) {
var msg;
if (/^Approve$/i.test(val)) {
msg = "Approve";
} else if (/^Approved$/i.test(val)) {
msg = "Approved";
} else if (/^Reject$/i.test(val)) {
msg = "Rejected";
} else {
msg = "Error";
}
alert(msg);
}
check("Approve");
check("Approved");
check("Reject");
check("Hello");
i want to validate numeric and allows the + (plus sign), but its not working
what i want
+63443 -> OK
8452 -> OK
s55sd -> Not OK
here's my code
var Nom = $("#addKonId1").val().split(" ").join("").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if (!intRegex.test(Nom)) {
alert("wrong Number");
} else {
alert(Nom);
}
Try This
var Nom = $("#addKonId1").val().trim(" ");
var intRegex = /^\+?\d+$/;
if(!intRegex.test(Nom)) {
alert("wrong Number");
}
else{
alert(Nom);
}
DEMO HERE
The regular expression for what you're looking for is:
^\+?\d+$
Which means "a string beginning with optionally one plus sign followed by one or more digits".
Your regex right now only tests for a string beginning with one or more digit characters. Alter intRegex like so:
var intRegex = /^\+?\d+$/;
On a side note, what you're doing in your first line with the replacing can simply be done with trim():
var Nom = $("#addKonId1").val().split(" ").join("").trim();
I have a string which is of format 245545g65.
var value = "245545g65"
var last3Letters = value.substring(7,9); // abc
Now I want to validate whether the last three letters contains only alphabets, if it is alphabet , i want to alert it.how to alert g?
how do i do this?
assuming that "contains only alphabets" means the last three characters are a combination of the letters a-z:
var str = '245545g65';
if (/[a-z]{3}$/.test(str)){
// last three characters are any combinations of the letters a-z
alert('Only letters at the end!');
}
you can use RegEx and compare length
var re = new RegExp("[^0-9]*", "g");
var newlast3Letters =last3Letters.replace(re,"");
if(newlast3Letters.length!=last3Letters.length)
{
alert("not all alphabets");
}
else
{
alert("all alphabets");
}
you can use isNaN to check weather s string is number
if (!isNan(last3Letters))
alert(last3Letters + ' is number.')
else
alert(last3Letters + ' is not number.')
You can also do this:
var value = "245545g65"
if(value.slice(value.length-3).search(/[^a-z]/) < 0) {
alert("Just alphabets");
} else {
alert("Not just alphabets");
}
Easy:
var alpha = /^[A-z]+$/;
alpha.test(last3Letters);
This will return a boolean (true/false). Stolen from here.
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