Testing for regexp match not working properly - javascript

I have a HTML form, and I wrote a JavaScript/jQuery script which tests if the field matches a regexp. However, what happens is that the regexp tester does not work and matches any string I input. Here's my code:
HTML
<input type="text" name="name" id="name" required>
<span id="namecheck"></span>
JS
$("#name").keyup(function () {
if (/^[A-Za-z \-]{0,35}/.test($(this).val())) {
$("#namecheck").html("<i style=\"color:green\">Match!</i>");
} else {
$("#namecheck").html("<i style=\"color:darkred\">No match!</i>");
}
});
JSFiddle
Since I'm kind of a newbie in JS (started learning it recently), I'm probably making some really dumb mistake but any help would be appreciated.

You probably want a $ at the end of your regular expression. A dollar sign indicates that it's the end of the string, so if you add that to your regex then it will only match strings with a length of 0 to 35:
/^[A-Za-z \-]{0,35}$/

Related

Regex not recognizing input value for vehicle license plate

I'm having a problem with my regex validation code. I'm trying to figure out how can I validate a vehicle license plate number. The code that I wrote is listed below this message. This is written down in React inline code and I've written down two different regex expressions and both of the come out to be false. The license plate number should be in this format XX-NNNN-XX.
X = Letter
N = Number
const [licencePlate, setLicencePlate] = useState('');
var ValidateLicencePlate = /^[A-Z][A-Z]-[0-9][0-9][0-9][0-9]-[A-Z][A-Z]$/g ;
var regex = /^[A-Z]{2}-[0-9]{4}-[A-Z]{2}$/g ;
<input name="licence-plate" type="text" className="feedback-input" maxLength='10' onChange={(e) => setLicencePlate(e.target.value.toUpperCase())} placeholder="XX-NNNN-XX"/>
This regex can solve the problem.
let regex = /^[A-Z]{2}-\d{4}-[A-Z]{2}/gi
This regex will match two alphabet at the beginning, four digits at the middle and two alphabet at the end.
You can use regex as following
<input pattern="/^[A-Z]{2}-\d{4}-[A-Z]{2}/g"/>
You can put your regex in the pattern attribute of the input element. I do not see you are using regexps yo have defined anywhere in your listing.
<input pattern={regex}/>
If you have a regex constraint to validate against it may be better and more comfortable to use Constraint Validation API.
<input pattern="your regex here"/>
Browser already validates everything in form elements if you constraint them with various ways like patter attribute and unless you tell it not to validate. But still I see many code bases trying to do the validation themselves. It is unnecessary since there is a way platform itself supports and does itself.

Textbox to accept only one #

I'm creating an email field in my html, can I only accept one #?
For example email:
chong!#$#gmail.com - should invalid because of there are others special characters included
or
ch#ng#gmail.com - should also be invalid because there are two #'s.
The only accepted special character should only be one #, how do I do this in javascript/jquery?
Sorry I really don't know much in regex. Or is there another way to validate an email format?
You can use the following regex in your input:
<input type="email" pattern="[a-zA-Z0-9.]+\#[a-zA-Z0-9.]+\.[a-zA-Z]+" />
This pattern avoid the user input an 'email' that don't fits with the email standard but also avoid limited the number of characters input in the name of user to 64 characters and the number of characters in the domain too.
^[A-Z0-9._%+-]{1,64}#(?:[A-Z0-9-]{1,63}.){1,125}[A-Z]{2,63}$
Some other patterns for validate numbers, numbers and letters and just letters:
^[0-9]+$
^[a-zA-Z0-9]+$
^[a-zA-Z]+$
Also you can use regular expression with javascript like this
Validate email address in JavaScript? and this other page its really useful for check if your regex pattern works correctly
http://regexr.com/
Try using this. It will open up a popup explaining the error if format is incorrect:
<form>
<input pattern="[a-zA-Z0-9.]+\#[a-zA-Z0-9.]+\.[a-zA-Z]+" title="Write your error here" />
<input type="submit" />
</form>
Hope this helps.

Javascript regex doesn't get validated on my site, but it does on validators

I'm literally hitting my head on the wall.
I have this regex pattern
(?:youtu\.be\/|youtube.com\/(?:watch\?.*\bv=|embed\/|v\/)|ytimg\.com\/vi\/)(.+?)(?:[^-a-zA-Z0-9]|$)
which extracts off the id of a youtube video. I tried it here
http://www.regular-expressions.info/javascriptexample.html
with any subject string, let's say http://youtube.com/watch?v=21312321 and it works.
However on my site, I have the following input field
<input type="text" name="status" id="status" placeholder="Post a youtube video link">
and the following jquery code
$('#status').keyup(function(event){
var value = $(this).val();
var pattern = "(?:youtu\.be\/|youtube.com\/(?:watch\?.*\bv=|embed\/|v\/)|ytimg\.com\/vi\/)(.+?)(?:[^-a-zA-Z0-9]|$)";
var re = new RegExp(pattern);
if (value.match(re)) {
console.log("Successful match");
} else {
console.log("No match");
}
});
and by using the same video as above, the result is "No match".
How is that even possible, please tell my what's going wrong here.
Use a regular expression literal instead:
var re = /(?:youtu\.be\/|youtube.com\/(?:watch\?.*\bv=|embed\/|v\/)|ytimg\.com\/vi\/)(.+?)(?:[^-a-zA-Z0-9]|$)/;
What’s happening is that a string already “evaluates” escapes, so your \. and \b are becoming . and the backspace character. new RegExp is the wrong function to use most of the time, and is only really useful when you have a dynamic regular expression (which is also wrong most of the time) — regular expression literals are more efficient, easier to read and therefore less error-prone.
(Also, youtube.com should probably be youtube\.com.)

JQuery validate website address input

I have an input text for a website address and I would like to validate it.
Examples of of what should be allowed are: www.somesite.com or .net or .org or anything valid for a website address.
Probably should use jQuery or just plain Javascript
Disclaimer : this is an extremely
naive implementation of a url
validation written in regex literal
javascript for the purpose of
explaining the thought behind such an
endeavor, this code is not intended
for production use in any capacity.
URL validation using regular expressions:
The following code will work for a cross section of cases. You will want to verify that those cases match your need. Urls are wide and varied creatures including possible usage of utf-8 characters not covered in the basic set below. For those cases you will want to investigate more about regex (totally worth doing in any capacity for javascript development anyway).
var urls = ['www.someurl.com', // true
'www.someurl.net', // true
'google.org', // true
'not a url', // false
'someone#funky.com', // false
'http://www.yahoo.com', // true
'https://www.clutter.org', // true
'ftp://test.fail', // false
'http://this.is.a/path/to/my/resource.html', // true
'adress-with-hyphens.org']; // true
for( var i = 0, url; url = urls[i++]; ){
console.log(url, /^(https?:\/\/)?([\w\d\-_]+\.)+\/?/.test(url));
}
to explain this code:
/ starts the regex literal.
( opens a selection group.
http is a string to search for.
s? makes the s part of the string optional.
: is a search of the colon character.
\/ is the escape character followed by the character to search for (/), this is useful in many cases.
)? makes the group optional.
The next group contains a lookup for any word, digit, hyphen or underscore character (one or more +), followed by a . (\.). followed by an optional /. / at the end closes the regular expression literal. test is a method on any regular expression object to see if a string passes it. The string to test is given as the only argument.
You want to use regular expressions.
Regular expressions are a pattern matching technology designed to search Regular Languages. What this means is you can use a Regular Expression to find and match many different things that fit your desired pattern.
A great place to start learning regex (short for Regular Expressions) at regular-expressions.info
They have amazing guides to get you started
Once you learn about them you will understand why this pattern
[www]?\..*?\.(com|net|org)
means and why it is not a great pattern to use to match a website although it would work.
Good luck and happy hunting
I noticed your title references jQuery - and while I assume this question is dead thought I'd post this for anyone else coming along. This jQuery plugin is simple to use and pretty powerful. While a plugin is overkill to validate a single field it can be helpful if you have other validation (including required fields) on the same form. The below example is pulled from the docs. After initing the plugin you simply add classes of what validation to include. You can create customs one if you need it but its a little more complex.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Usage is simple:
$("#commentForm").validate();
form:
<form class="cmxform" id="commentForm" method="post" action="">
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
</p>
<p>
<label for="curl">URL</label>
<em> </em><input id="curl" name="url" size="25" class="url" value="" />
</p>
<p>
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit"/>
</p>
</form>
And thats it XD
$.ajax({url: webpage ,type:'HEAD',error:function(){
alert('Oops !');
}});

What did I do wrong here? [Javascript Regex]

So I am writing a registration form and I need the display name to be only numbers, letters and underscores.
Have a look at my code and tell me what I'm doing wrong.
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+/
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus()
alert("Your display name may only contain letters, numbers and underscores")
return false
}
}
-->
</script>
It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.
Your regex
/^([a-zA-Z0-9_])+/
Looks for
Start of string(check), followed by
1 or more letters, numbers, or underscore (check)
And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore
If you put a $ at the end, then it will work - $ matches 'end of string', so the only way it can match is if there are only numbers, letters, and underscores between the start and end of the string.
/^([a-zA-Z0-9_])+$/
Secondly, I'd suggest using document.getElementById('display-name').value instead of document.forms as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'
My regexp would go along the lines of: /^[a-zA-Z0-9_]+$/
edit: I think it's the lack of a line end $ that makes it fail.
What does "doesn't work" mean? Does it reject valid display names? Does it accept invalid display names? Which ones?
Per #Annan, leaving off the $ would make the regexp accept invalid display names like abc123!##.
If the code is rejecting valid display names, it may be because the parentheses are being matched literally instead of denoting a group (I'm not sure of the quoting convention in JS).
A simpler way to write it still would be
var name_regex = /^([a-z0-9_])+$/i;
Even simpler:
var name_regex = /^\w+$/;
I tested your script and meddled with the javascript. This seem to work:
<form method="post" action="/" onsubmit="return check_form()">
<input type="text" id="display-name" name="display-name" maxlength="255" />
<input type="submit" />
</form>
<script type="text/javascript">
<!--
var name_regex = /^([a-zA-Z0-9_])+$/;
function check_form()
{
if (!name_regex.test(document.forms[0].elements[0].value))
{
document.forms[0].elements[0].focus();
alert("Your display name may only contain letters, numbers and underscores");
return false;
}
}
-->
</script>
Sorry guys I should have been more specific. Whenever I added spaces the values were still being accepted. The dollar sign $ did the trick!
By 'not working' I take it you mean it is letting invalid entries through (rather than not letting valid entries through).
As #Annan has said, this would probably be due to the lack of the $ character at the end of the expression, as currently it only requires a single valid character at the start of the value, and the rest can be anything.

Categories