Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to allow letters, numbers, periods, hyphens, underscores, and spaces

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>
like image 568
ryansd Avatar asked Dec 10 '22 13:12

ryansd


2 Answers

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()">
like image 100
GantTheWanderer Avatar answered May 19 '23 15:05

GantTheWanderer


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

like image 20
MeNotMe Avatar answered May 19 '23 16:05

MeNotMe