jquery regex continuous space [duplicate] - javascript

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 5 years ago.
I want to check input and want to show error if input is empty or entered continuous space. just one space allowed between words. e.g:
Test ok test
var pattern = /\s\s+/g;
$('a').click(function() {
if ($('input').val().length <= 2 || pattern.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type="text"/>
It seems working, but it have issue, do this to find this issue:
Enter 5 space continuously, then click on check, it alert error but click again on check, it alert ok.
should error when user entered more than 2 space continuously.

you can use trim method which will work better than your code in the if statement .
The trim() method removes white space from both ends of a string which in this case the value of the input , after that you can check if its equal to the empty string and will work fine
see the example below
var pattern = /\s\s+/g;
$('a').click(function() {
if ($('input').val().trim()==='') {
alert('error');
} else {
alert('ok go');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>check</a>
<input type ="text" />

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test:
If the regex has the global flag set, test() will advance the lastIndex of the
regex. A subsequent use of test() will start the search at the substring of str
specified by lastIndex (exec() will also advance the lastIndex property).
The problem is after your regex is matched against the string, the lastIndex property will cause the next match to start after the previous match. You can verify this by outputting the value of pattern.lastIndex after each click.
You can fix this by manually setting lastIndex back to zero after each match, like
$('a').click(function() {
pattern.lastIndex = 0;
if ($('input').val().length <= 2 || pattern.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
You can also fix by getting rid of pattern all together and writing
$('a').click(function() {
if ($('input').val().length <= 2 || /\s\s+/g.test($('input').val())) {
alert('error');
} else {
alert('ok go');
}
});
Note that you can change your pattern to /\s{2,}/g matching whitespace two or more times.

Related

Remove last character on input field jQuery

I know this kind of question has been asked several times but none of the answers worked for me. I want to make my own spell-checker which compares words letter by letter and checks the correctness.
As user types letters one by one, the content is checked. If it is correct, goes on, if it is wrong: I want the last letter to be deleted.
Here is my code:
var word = [];
word = "beautiful".split('');
var i =0;
$(document).ready(
function()
{ $('#txtword').keyup(
function() {
var value = document.getElementById('txtword').value;
if (value[i] == word[i]){
alert("Right letter!");
i++; }
else
{ alert("Wrong letter");
value.slice(0,-1);
/*value.substr(0,value.length-1);*/
}
});
})
I tried both options value.slice(0,-1); and value.substr(0,value.length-1); but they are not working. Can someone help me find the mistake!
You need to assign new value back to value property of the element
this.value = value.substr(0,value.length-1);
Note: You can use this.value instead of document.getElementById('txtword').value;

Find all instances and display alert - part 2, now with regex

Thanks for your help with my earlier question:
How to find all instances and display in alert
Now I discover that I need to include some invalid character validation.
I'm trying to figure out how to include a set of regex invalid characters as part of the validation that will also show up in the same alert/textbox/whatever as the "too long/too short" validation.
So, I have a textbox which users will type or paste comma separated values such as AAAAAAA,BBBBBBB,CCCCCCCC,DDDDDDDD
And they cannot be more or less than seven characters long and they can only include certain characters.
I currently have have two separate pieces of Javascript that I'm trying to now combine:
var Invalidchars = "1234567890!##$%^&*()+=[]\\\';./{}|\":<>?";
for (var i = 0; i < document.getElementById("TextBox1").value.length; i++) {
if (Invalidchars.indexOf(document.getElementById("TextBox").value.charAt(i)) != -1){
alert
and this
var val = document.getElementById("Textbox1").value,
err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
return true;
Any help is much appreciated!
=================================================
SOLUTION
Took a while, but using Tenub's code (which didn't quite combine my two sets code, but was close enough), I finally figured out how to merge my two sets of code into one. Here's the code if anyone is ever interested in using it:
var val = document.getElementById("TextBox1").value,
err = $.grep(val.split(','), function(a) {return (a.length = (!/^[^0-9!##$%^&*()+=;.\/\{}|:<>\\?\[\]\'\"]{7}$/.test(a)));});
if (err.length){
document.getElementById("DIV1").style.display = "inline-block";
document.getElementById("TextBox2").value = err.join(',');
return callback (false);
}
document.getElementById("DIV1").style.display = "none";
return true;
The answer is as simple as it is elegant:
var val = document.getElementById("Textbox1").value;
if(!/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test(val)) {
// handle invalid value
}
This tests that the string is 7 characters in length and does not contain any character within the brackets after the "^" (also some characters are escaped with a "\").
You can test in console:
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adfFDKZ'); // returns true
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adf(DKZ'); // returns false
Try this:
/*
* This regex matches all the invalid characters. I escaped the
* special characters.
*/
var regex = /.*[0-9!##\$%\^&\*\(\)\+=\[\]\\';\./\{\}\|":\<\>\?]+.*/;
var text = document.getElementById("TextBox1").value;
/* Test for match...much faster than a for-loop under any circumstances */
if (text.matches(regex)) {
alert("Invalid characters present. Please correct the input");
return false;
}
/* split on delimiter */
var err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
Please tell me if there are any bugs in this. Also, the only real way to test for this in one step is to set up an enormously long regex. Also, with only one check, it would make it a little harder to guide the user to make the right correction. I will mention that.

Javascript Replace - Regular Expression

I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}

Regular expression to verify zip code and checking for invalid characters

I am trying to validate an input for zip codes, now this zip code should work for US, CANADA, UK, all the countries but omit any special characters, so i tried, checking for invalid characters first if that passes then i check for the zip code to either be US or if not just to make sure there are valid characters and not more than 8 (space in between them is ok as long as its now US(which includes - for 5 + 4)
The problem I am having is that 11215 for example is returning as false for the valid character validation and 11215## is returning false also.
Here are my regex:
var reg1 = /^[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]+$/;
var reg2 = /(^\d{5}$)|(^\d{5}-\d{4}$)|(([a-z0-9]{8})*$)/
var isOk = reg1.test("11215"); // returns false!
if(isOk)
{
isOk = isOk && reg2.test("11215");
}
var isOk2 = reg1.test("11215##"); // returns false also!
if(isOk2)
{
isOk2 = isOk2 && reg2.test("11215##");
}
The test for "bad chars", reg1 will always be false unless your string is made entirely of "bad chars". I don't think this is the behaviour you wanted.
var matchBad = /[^\s\da-z\-]/i;
// Match all non-whitespace, non-digit, non-alpabet, non-hyphen
if (false === matchBad.test("11215")) { // no bad chars detected
console.log('pass!');
// continue checking validity..
} else { // bad chars detected
console.log('fail!);
}
Your first regex is testing whether the entire string has those characters. If you want containment, remove the ^ and $ denoting the beginning and ending of your regex:
var reg1 = /[\^$%#!#&\*:<>\?\/\\~\{\}\(\)\+|]/;
This may be only part of the problem but it should get you somewhere. Note I also removed the + since it really only needs to match one character to detect a bad character.
Also another note of design. Your regex that exactly matches the pattern should really be sufficient for testing this. I'm not quite familiar though with the third type of zip, but you might want to make it capture the entire string (with ^ and $)
Javascript should be like below
<script type="text/javascript">
function IsValidZipCode(zipcode) {
var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zipcode);
if (!isValid){
alert('Invalid ZipCode');
document.getElementById("zipcode").value = "";
}
}
</script>
Zipcode text should be
<input id="zipcode" class="zipcode" type="text" placeholder="Your Zipcode?" name="zipcode" onchange="IsValidZipCode(this.form.zipcode.value)" required >

Use "^" to check if string begins with another string? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
javascript - check if string begins with something?
I've read in this post that you can use ^= to check if a string begins with something.
I've fiddled with this example:
var foo = "something-something";
if(foo ^= "something") {
alert("works!");
}
else{
alert("doesn't work :(");
}
And it doesn't work - does anyone how to do this?
jsfiddle example here: http://jsfiddle.net/timkl/M6dEM/
I think, perhaps, you were thinking of:
var x = "hello world!"
if (x.match(/^hello/)) {
alert("I start with it!")
}
This uses an anchored (^) regular expression: it must find "hello" at the start of the input to match.
On the other hand, x ^= "foo" is the same as x = x ^ "foo", or a bit-wise exclusive or. In this case that is equivalent to x = "something-something" ^ "something" -> x = 0 ^ 0 -> 0 (which is a falsey value, and never true).
Happy coding.
var foo = "something-something";
if(foo.indexOf("something") === 0) {
alert("works!");
}
else{
alert("doesn't work :(");
}
See updated jsfiddle http://jsfiddle.net/M6dEM/3/
Use substring() method.
if(foo.substring(0,"something".length) == "something") {
alert("works!");
}
else{
alert("doesn't work :(");
}
I edited my answer and replaced "9" with "something".length so now there's no hardcode anymore.

Categories

Resources