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>
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()">
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With