Reputation: 43
I'm trying to affix form data (username) to a url. On the site, a username can consist of letters, numbers, spaces, hyphens, underscores, and periods.
I'm trying to create a javascript regex that allows those characters, but only those characters.
What I have so far will allow, for example:
User Name
But it will also allow, User Name&
I've searched many stackover flow posts but have not yet solved this. Thank you very much for your suggestions. Here is what I have..
<script>
function process() {
var regexp1=new RegExp("[^[0-9A-Za-z_.-]+$]");
var url = "http://www.website.com/page.php?data=" + document.getElementById("url").value;
if (regexp1.test(document.getElementById("url").value)) {
alert("Only numbers, letters, hypens, periods, spaces and underscores are allowed");
return false;
}
location.href = url;
return false;
}
</script>
<form onSubmit="return process();">
<br>
<input type="text" size="10" maxlength="30" name="url" id="url">
<input type="submit" value="go">
</form>
Upvotes: 4
Views: 12158
Reputation: 1292
Your if statement is reversed. You should check when the regex DOES NOT match instead:
!regexp1.test(document.getElementById("url").value)
Also I believe the original regex is wrong/inaccurate try the one shown below:
function process() {
var regexp1=new RegExp("^[0-9A-Za-z_.-]+$");
var url = "http://www.website.com/page.php?data=" + document.getElementById("url").value;
if (!regexp1.test(document.getElementById("url").value)) {
console.log("Only numbers, letters, hypens, periods, spaces and underscores are allowed");
} else {
console.log("Passed validation.");
}
}
<input type="text" size="10" maxlength="30" name="url" id="url">
<input type="button" onclick="process()">
Upvotes: 5
Reputation: 147
Your regex should be :
/^[ A-Za-z0-9_-.\s]*$/i
Explanation :
^ : Begging of string
A-Z : Uppercase Characters
a-z : Lowercase Characters
0-9 : Numbers
_-. : Special Characters you requested
\s : Spaces
* : Allow repeat
$ : End of string
/i : Case insensitive
You can replace A-Za-z0-9_
with \w
And your If stament should check for the inverse :
if(!regexp1.test...
And at the end of the function it's better to make it
return true;
I suggest you check JQuery for more advanced, easier Javascript code
Hope this help
Upvotes: 5
Reputation: 7361
as far as the regex you need to anchor it with ^
and $
to make it mean "whole thing" and avoid partial mathching, also your space is outside the character class and should be in. Additionally, we can get 'letters/numbers/underscore' with \w+
, even inside a character class. Finally we can make use of the i
flag to not worry about capitalized letters:
/^[\w\s.-]+$/i
https://regex101.com/r/47l22K/1
Upvotes: 4