What did I do wrong here? [Javascript Regex] - javascript

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.

Related

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.

Testing for regexp match not working properly

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}$/

Force different characters at different positions

I'm currently working on a project in which I need to fetch street/city details from a DB using a zipcode. Dutch zipcodes use a "1111 AA" format, I would like to have this entered in a single input field while forcing the first four characters to be numeric and the last two to be alphabetical.
I've been googling this quite a bit, have found ways to force either one, but none to combine it into a single input field and I don't seem to be crafty enough to combine them myself.
Thank you.
We use this in alot of sites, especially for phone #s
http://digitalbush.com/projects/masked-input-plugin/
To handle the specific pattern you entered, try something like this in the javascript function that validates form input:
var pattern = new RexExp( '[0-9]{4} [A-Z]{2}' );
if( inputFieldValue.search( pattern ) == -1 )
{
// throw error condition.
}
else
{
// The pattern matched. Continue on.
}
This is finally a question where regular expressions are a suitable solution.
Try this:
var zip = "1111 AA"
var regex = new RegExp("^[0-9]{4}\\s?[A-Z]{2}$");
regex.test(zip);
Note that this will not allow lowercase characters, and will allow the zipcode without whitespace (like this: 1111AA). Try some googling to find out how to allow or disallow those.
You can use the new html5 pattern attribute for that:
<form>
<input name="zipcode" type="text" pattern="\d{4}\s?[A-Z]{2}" length="7" />
<input type="submit" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​
If the attribute isn't supported, you fall back to a javascript solution, checking the input field with a regex before submit like the following:
var pattern = /[0-9]{4}\s?[A-Z]{2}/;
string.match(pattern);
Take a look at the demo fiddle.

Javascript input validation

How do I ensure that there are no special characters in the name except an apostrophe...Eg:- I can allow O'Connor but not John "Doe" ? Please help.
Use a regular expression, if you want only English characters with an apostrophe use ^[A-Za-z\']*$ you can extend this to check for a LOT of things. Regular Expressions are a very powerful tool and I'd advise reading up on them(they exist in pretty much every programming language)
var validRegex = /^[A-Za-z\']*$/;
if(myString.search(validRegex)==-1)
alert("Error");
Edit: added example.
Here's a working example of how you'd use a regular expression to check for a valid name given the conditions you laid out:
<!DOCTYPE html>
<html>
<head>
<title>Check for a good name</title>
<script>
var goodName = /^[A-Za-z'\s]+$/;
function checkName(name){
if (goodName.test(name)) {
alert("Name is great!");
} else {
alert("Name contains illegal characters");
}
}
</script>
</head>
<body>
<form onsubmit="return false;">
<input type="text" name="name" size="20">
<input type="button" value="Check"
onclick="checkName(this.form.name.value);">
</form>
</body>
</html>
The /^[A-Za-z'\s]+$/ regular expression allows uppercase English, lowercase English, apostrophes, and spaces. (It's similar to the one proposed by Afiefh, with the addition of the \s to allow spaces, and the + instead of the * to prevent blank names from passing the test.)
As David Dorward suggests above, if you really are using this to test names, you might consider relaxing the rule to accommodate international names by changing line 6 to this:
var goodName = /^([ \u00c0-\u01ffa-zA-Z'\-])+$/;
This allows unicode characters, apostrophes, and hyphens.

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 !');
}});

Categories