Javascript validate string is a character followed by numbers - javascript

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)}`)
})

Related

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()" />

javascript regex validation function

My java-script regex validation requires the following condition.
Accept only alphabet value
Do not accept only numeric value
Do not accept only special characters
Accept combination of alphanumeric and special character value
I wrote following code to achieve it
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
if (filter.test(str)) {
return true;
}
else {
return false;
}
}
and I also tried different regex but never achieved the desired result.
Please do help me with the proper regex for my validations.
Thank You
Since, It is necessary to have alphabets in your string, simply check for that
function validateAlphaNumChar(str) {
var filter = /^[ A-Za-z0-9_##./#&+-]*$/;
var filterAlphabets = /^[ A-Za-z]*$/;
if (filter.test(str)) {
if ( filterAlphabets.test(str)){
return true;
}
else{
return false; }
}
else {
return false;
}
}
This is assuming that a combination of numbers and special characters is not allowed
If i understood the question right it should be like this
Check if it contains only numbers
Check if it contains only special symbols
function validateAlphaNumChar(str) {
var filterABC = /^[A-Za-z]*$/;
var filterNUM = /^[0-9]*$/;
var filterSPEC = /^[_##./#&+-]*$/;
if (filterNUM.test(str)) {
return false;
} else if(filterSPEC.test(str)) {
return false;
} else {
return true;
}
}
document.getElementById("demo").innerHTML = validateAlphaNumChar("A#");
<p id="demo"></p>

Trouble with easy Coderbyte challenge counting x's and o's

I'm new to JavaScript and not sure why my code isn't working. I'm trying to return true if there are an equal amount of x's and o's, and return false if there are not. My code works for all inputs except "x" and "o". Any help is appreciated!
My code:
function ExOh(str) {
var x = str.match(/[^x$]/gi);
var o = str.match(/[^o$]/gi);
if (x.length == o.length) {
return true;
}
else {
return false;
}
}
Your regexps allow any characters other than x/y and $. You must have meant /x/gi and /o/gi.
function ExOh(str) {
var x = str.match(/x/gi) || "";
var o = str.match(/o/gi) || "";
if (x.length === o.length) {
return true;
}
else {
return false;
}
}
alert(ExOh("zzz"));
alert(ExOh("oozzzxx"));
Note that negated character classes like [^x] match all characters other than those inside the square brackets. $ inside them is treated as a literal dollar sign.
Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class. Unlike the dot, negated character classes also match (invisible) line break characters. If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break.
You need to set the value to something other than null if the str.match doesn't actually match something. You can't call length on null. Use the or operator to set the value to an empty string in your variable declaration.
function ExOh(str) {
var x = str.match(/[^x$]/gi) || '';
var o = str.match(/[^o$]/gi) || '';
if (x.length == o.length) {
return true;
}
else {
return false;
}
}
I hope this helps
Here's a solution for checking that the number of two characters is the same.
// How many 'x' characters occur in a string?
function numberOf(str, x) {
var matches = str.match(new RegExp(x, 'g'));
return matches ? matches.length : 0;
}
// Create a function to check if the number of x's and o's in
// a string are the same.
function same(x, o) {
return function(str) {
return numberOf(str, x) === numberOf(str, o);
};
}
var isSame = same('x', 'o');
isSame('xxooabc');
Remove ^ and $ from your regex , [^o$] match a single character not o or $. You just need to use /x/ and /o/ and flags ig, i for ignoring case and g for global match.
Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class. Unlike the dot, negated character classes also match (invisible) line break characters. If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break. ( Taken from http://www.regular-expressions.info/charclass.html )
Update : Add (!x && !o) and x && o in condition for avoiing error when zero matches are there. (!x && !o) for when both are not present.x && o will help only to check the condition x.length == o.length when both x and o are defined.
var div = document.getElementById('res');
function ExOh(str) {
var x = str.match(/x/gi);
var o = str.match(/o/gi);
if ((!x&&!o) || x && o && x.length == o.length) {
res.innerHTML = 'Same';
return true;
} else {
res.innerHTML = 'Not Same';
return false;
}
}
<input type=text oninput="ExOh(this.value)">
<div id=res></div>

Check Space in String

I want to check that if my username contains space so then it alert so i do this it work but one problem i am facing is that if i give space in start then it does not alert.I search it but can't find solution, my code is this
var username = $.trim($('#r_uname').val());
var space = " ";
var check = function(string){
for(i = 0; i < space.length;i++){
if(string.indexOf(space[i]) > -1){
return true
}
}
return false;
}
if(check(username) == true)
{
alert('Username contains illegal characters or Space!');
return false;
}
Just use .indexOf():
var check = function(string) {
return string.indexOf(' ') === -1;
};
You could also use regex to restrict the username to a particular format:
var check = function(string) {
return /^[a-z0-9_]+$/i.test(string)
};
You should use a regular expression to check for a whitespace character with \s:
if (username.match(/\s/g)){
alert('There is a space!');
}
See the code in action in this jsFiddle.
why you don't use something like this?
if(string.indexOf(space) > -1){
return true
}

Javascript IndexOf with integers in string not working

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

Categories