I need to flag a textarea that contains a URL starting with http://, but not with https://. I thought this should work, but I'm getting the alert even when all URLs are https.
$('#template_form').submit(function() {
alert("this is the text: " + $("#template_data").val() );
val = $("#template_data").val();
if (val.search(/^http:\/\//)){
alert("there's a URL in there...");
return false;
}
return true;
});
<textarea id="template_data">This is a test of the new URL validation. Let's add a link to https://www.test.com</textarea>
This should only present the second alert if the URL were http://www.test.com, but it's throwing it even as is, with https://. What am I doing wrong?
From the documentation for search():
A String method that tests for a match in a string. It returns the index of the match, or -1 if the search fails.
-1 will make the if statement evaluate to true (if (-1) {alert("true");}. So either switch to match() or test(), or check for if (val.search(...) > -1)
Also the ^ is wrong in your regex, it would only match from the start of the string.
$('#template_form').submit(function() {
alert("this is the text: " + $("#template_data").val());
val = $("#template_data").val();
if (val.match(/http:\/\//)) {
alert("there's a URL in there...");
return false;
}
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="template_form">
<textarea id="template_data">This is a test of the new URL validation. Let's add a link to https://www.test.com</textarea>
<input type="submit" value="submit">
</form>
String.search() is not boolean:
Return value
The index of the first match between the regular expression and the given string; if not found, -1.
Further in that same piece of documentation:
When you want to know whether a pattern is found and also its index in
a string use search() (if you only want to know it exists, use the
similar test() method, which returns a boolean)
$('#template_form').submit(function() {
if ($("#template_data").val().indexOf("http:\/\/") > -1) {
return false;
}
return true;
});
Here is another way.
Related
If i am giving Special Symbol only at beginning then it's working otherwise it's not working.
For example:
var password = '#Sourav12345'
if (password.search(/[#_!#$%^&*()<>?/\|}{~:]/)) {
return true
}
else{
return false
}
If i will change password to Sourav#12345.it won't work .Plz. help me
Your regex should work perfectly fine, the issue you are probably encountering is that search() returns the index if the first matched occurencens found, otherwise -1.
So only your case where # is the first character will evalute to false in your condition. You would need to adapt your condition:
var password = 'Sourav12345#.it'
var search = password.search(/[#_!#$%^&*()<>?/\|}{~:]/);
if (search >= 0) {
console.log(true)
}
else{
console.log(false)
}
Or use a different mehtod to check against a regex like test()
var password = 'Sourav12345#.it'
var test = /[#_!#$%^&*()<>?/\|}{~:]/.test(password);
if (test) {
console.log(true)
} else {
console.log(false)
}
This is the correct regex:
/[#_!#$%^&*()<>?\/\|}{~:]/
Just escaped the "/" to make it work
The search() method searches a string for a specified value and returns the position of the match.
if it is not found it will return -1 else it returns the position number
var x='#Sourav12345'.search('/[#_!#$%^&*()<>?/\|}{~:]/') > 0?true:false;
console.log(x)
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.
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;
}
}
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 >
I'm trying to find some text in a long string but my code does not work, For Example:
Var result = “<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN html><head<title>Hey i am here</title>”
if (result.search('Hey i am here')== true) {
alert('found');
} else { alert('NOT found'); }
But This dont Works :(
Please help
var is lower case
Strings can be delimited with " or ' but not with “, don't use curly quotes.
The search method expects a regular expression (although it will try to convert a string if it gets one)
If you want a simple string match, then indexOf is more efficient then search.
Both search and indexOf return the index of the first match (or -1 if it doesn't find one), not a boolean.
As an aside, that Doctype will trigger quirks mode, so never use it in a real HTML document.
var result = "<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN html><head<title>Hey i am here</title>"
if (result.indexOf("Hey i am here") >= 0) {
alert('found');
} else {
alert('NOT found');
}
I thinks you need to use an .indexOf function.
so your if statement would be
if (results.indexOf('Hey i am here') != -1) {
alert('found');
} else { alert('NOT found'); }
There are a lot of ways to do this:
See here
Search method returns the position of the match, or -1 if no match is found. Not true or false.