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
}
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()" />
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>
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 have a JavaScript String, for example :
var test1 = "aaaaaa#bbbbb.temp" ; // Function must return true in this case
var test2 = "ccccc#ddddd.fr " ; // Function must return false in this case
I would like to build a function which return true if the String contains # character, following by any character "bbbbbb" following by ".temp" extension.
How can I do this ?
You can use regex#test
var found = /#.*?\.temp\b/.test(str);
If you want to make it # character, following by "bbbbbb" following by ".temp" extension then use:
var found = /#bbbbbb\.temp\b/.test(str);
Regular expression solution:
function validate(argument) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if((argument.lastIndexOf('.temp', argument.length-5)>=argument.length-5) && re.test(argument)) {
return true;
} else {
return false;
}
}
JsFiddle test: http://jsfiddle.net/2EXxx/
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.