if i run, validation just can be work only on symbol "/", if I input the other symbol except / didnt working. I'm not use regex.
if(nama!==""){
var i;
var list = new Array ("/","!", "#", "#","$","%","%","^","&","*",
"(",")","_","+","=","-","`","~",";","<",
">",".","?","[","]","{","}",",");
var llength = list.length;
for(i=0; i<llength; i++)
{
if(nama.match(list[i]))
{
alert("Full Name must not contain any number and symbol");
return false;
}
else
{
return true;
}
}
}
There seem to be several problems here. One is that you are calling return true as soon as you reach a valid character. That means that you'll never check anything else if the first letter is valid.
Another problem is that you are trying to check for invalid characters, but how can you know you've checked them all?
A better approach to the whole problem might be to only a list of valid letters; The changes to your original could might be something like the following:
var list = new Array ("a", "A", "b", "B", ... [etc] );
for(i=0; i<llength; i++)
{
if(!nama.match(list[i]))
{
alert("Full Name can only contain letters a-z!");
return false;
}
}
This should only quit the loop (and the containing function) when an invalid character is encountered.
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'm currently working with Javascript and for now I'm searching a way to check if variable contains at least one string. I have looked at previous questions, however, neither contain what I'm looking for. I have a function here:
function findCertainWords()
{
var t = {Some text value};
if (t in {'one':'', 'two':''})
return alert("At least one string is found. Change them."), 0;
return 1
}
Variable a is user's written text (for example, a comment or a post).
I want to check if user has written certain word in it and return an alert message to remove/edit that word. While my written function works, it only works when user writes that word exactly as I write in my variable ("Three" != "three"). I want to improve my funtion so it would also find case-insensitive ("Three" == "three") and part of words (like "thr" from "three"). I tried to put an expression like * but it didn't work.
It would be the best if every expression could be written in one function. Otherwise, I might need help with combining two functions.
Use indexOf to test if a string contains another string. Use .toLowerCase to convert it to one case before comparing.
function findCertainWords(t) {
var words = ['one', 'two'];
for (var i = 0; i < words.length; i++) {
if (t.toLowerCase().indexOf(words[i]) != -1) {
alert("At least one string was found. Change them.");
return false;
}
}
return true;
}
Another way is to turn the array into a regexp:
var regexp = new RegExp(words.join('|'));
if (regexp.test(t)) {
alert("At least one string was found. Change them.");
return false;
} else {
return true;
}
You can use Array.some with Object.keys
if(Object.keys(obj).some(function(k){
return ~a.indexOf(obj[k]);
})){
// do something
}
Hi I'm new to JavaScript and I'm a little stuck trying to get this code to work. I'm stuck with the last part where I check the array to see if it contains those selected characters and if it does alert true and if not alert false.
var userinput = prompt('Input characters:');
var lowercase = userinput.toLowerCase();
alert(lowercase);
var allowedcharacters = [a,b,c,d,e,f];
if (lowercase){
alert(true)
}
else{
alert(false)
}
if you want to check that your input just contains these characters you can do this using a regex.
This could be done like the following:
if (lowercase.match(/[abcdef]*/) == lowercase) {
//Just contains allowed Characters
}
else {
//contains forbidden characters
}
And in case you want to search if there is any allowed character you would do it like this:
if (lowercase.search(/.*[abcdef].*/) != -1) {
//Contains at least one allowed character
}
else {
//contains none of them
}
EDIT
This works fine if you know you'll always be using [abcdef], but would suddenly break if you change allowedcharacters to be ["u", "v", "w", "x", "y", "z"]. To make it more generic, build the regular expression differently. For the first one, you would do:
if (lowercase.match(RegExp("[" + allowedcharacters.join("") + "]*")) == lowercase) {
// ...
And the second one would be similar:
if (lowercase.search(RegExp(".*[" + allowedcharacters.join("") + "].*")) != -1) {
// ...
In this way, your allowedcharacters can be anything, since joining the array as indicated will put all the variables together without any spaces or commas.
EDIT
Here you find a running example: http://jsfiddle.net/Florian_Loch/YR8pw/
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 to check if the number of open braces is equal to the number of close braces using regular expressions?
Here is the code:
var expression1 = "count(machineId)+count(toolId)";
var expression2 = "count(machineId)+count(toolId))";
These are the 2 expressions, where in the expression1, the number of open brackets is equal to number of close brackets and in expression2, the number of open brackets is not equal to number of close brackets. I need a regular expression which counts the number of open brackets and close brackets and gives me the alert. I need to check for valid syntax too.
if(expression1.......){ // here goes the regular expression
alert("Matched");
}
else{
alert("Not matched");
}
var expression1 = "count(machineId)+count(toolId)";
var expression2 = "count(machineId)+count(toolId))";
if (matches(expression1)) {
alert("Matched"); // Triggered!
}
else {
alert("Not matched");
}
if (matches(expression2)) {
alert("Matched");
}
else {
alert("Not matched"); // Triggered!
}
function matches(str) {
try {
new Function(str);
return true;
}
catch (e) {
return !(e instanceof SyntaxError);
}
}
This works because new Function() will cause a syntax error if your code is wrong. Catching the error means you can handle it safely and do whatever you want. Another good thing is that it doesn't execute the code, it just parses it. Basically, you're leveraging your task to the browser's parser.
It doesn't use regex, but it does check if your code is valid. Thus, it tells you if the parentheses match.
Task can be simply solved without regexp, just count braces.
var a = 'count(machineId)+count())toolId)'
var braces = 0;
for (var i=0, len=a.length; i<len; ++i) {
switch(a[i]) {
case '(' :
++braces;
break;
case ')' :
--braces;
break;
}
if (braces < 0) {
alert('error');
break;
}
}
if (braces)
alert('error');
If your goal is to check if an expression is valid (it also means its substring that contains only brackets forms a correct bracket sequence), then regexps won't help you.
Regular expressions can only handle so called "regular languages" (though JS regexps maybe somewhat more powerful than their theoretic counterparts, the price of such power is greater complexity) while language of correct bracket sequences isn't regular.
See those slides — they can give you a glimpse into why regular expressions cannot recognize correct bracket sequence.
Nevertheless, the problem isn't so hard. You should just maintain a stack and go over your string from the left to the right. Every time you meet an opening bracket, you push it to the stack. When you meet a closing bracket, you pop top element of the stack and check if its type matches your one (yes, this algorithm can handle brackets of multiple types). At the end you should just check if the stack is empty.
In case you don't need to handle different types of brackets (you have only '(' and ')', for example) you can just maintain a variable openBrackets (essentially it would represent stack's size) and don't let it become negative.
if (expression1.match(/\(/g).length === expression2.match(/\)/g).length) {
// is equal
}
In order to make it work with strings containing no braces, you may use the following workaround:
((expression1.match(/\(/g) || []).length
If you only care about the count why don't you try something like this.
if(expression1.split('(').length == expression1.split(')').length) {
alert('matched');
}
Here's another way to do it:
function validParenNesting(text) {
var re = /\([^()]*\)/g; // Match innermost matching pair.
// Strip out matching pairs from the inside out.
while (text.match(re))
text = text.replace(re, '');
// If there are any parens left then no good
if (text.match(/[()]/))
return false;
// Otherwise all parens part of matching pair.
return true;
}
"I need to match the no of open braces equal to no of close braces using regular expression"
"I need to check for the valid syntax too."
If 2 is true, then 1 is also true. So, look for matches for what you know is valid syntax -- in this case: {}. Execute a loop which removes all valid matches from the "stack" until there are no valid matches left. If what's left at the end is nothing, then it means your argument is 100% valid. If what's left at the end is something -- it means the "remainders" didn't pass your validity test, and are thus invalid:
var foo = function(str) {
while(str.match(/{}/g)) // loop while matches of "{}" are found
str = str.replace(/{}/g, ''); // "slices" matches out of the "stack"
return !str.match(/({|})/g); // `false` if invalids remain, otherwise `true`
};
foo('{{{}}}'); // true
foo('{{}}}}}}}}}}{}'); // false
Try ...
function matchBraces(s) {
return s.match(/\(/g).length === s.match(/\)/g).length;
}
... then, your code for the alerts would be as follows ...
if(matchBraces(expression1)) {
alert("Matched");
} else {
alert("Not matched");
}
Working copy: jsFiddle
The following can be applied to find the number of brackets.
However, it does not use RegExp and uses simple logic.
var l = 0;
var r = 0;
//Count the number of brackets.
for(var i=0;i<str.length;i++){
if(str[i]=="("){
l++;
}
else if(str[i]==")"){
r++;
}
}
if(l==r){ //The number of opening and closing brackets are equal.
doSomething();
}