Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex validation rules

I'm writing a database backup function as part of my school project.

I need to write a regex rule so the database backup name can only contain legal characters.

By 'legal' I mean a string that doesn't contain ANY symbols or spaces. Only letters from the alphabet and numbers.

An example of a valid string would be '31Jan2012' or '63927jkdfjsdbjk623' or 'hello123backup'.

Here's my JS code so far:

    // Check if the input box contains the charactes a-z, A-Z ,or 0-9 with a regular expression.

    function checkIfContainsNumbersOrCharacters(elem, errorMessage){
        var regexRule = new RegExp("^[\w]+$");
        if(regexRule.test( $(elem).val() ) ){ 
            return true;
        }else{
            alert(errorMessage);
            return false;
        }
    }


//call the function

checkIfContainsNumbersOrCharacters("#backup-name", "Input can only contain the characters a-z or 0-9.");

I've never really used regular expressions before though, however after a quick bit of googling i found this tool, from which I wrote the following regex rule:

^[\w]+$

^ = start of string

[/w] = a-z/A-Z/0-9

'+' = characters after the string.

When running my function, the whatever string I input seems to return false :( is my code wrong? or am I not using regex rules correctly?

like image 349
Joel Murphy Avatar asked Mar 01 '26 20:03

Joel Murphy


1 Answers

The problem here is, that when writing \w inside a string, you escape the w, and the resulting regular expression looks like this: ^[w]+$, containing the w as a literal character. When creating a regular expression with a string argument passed to the RegExp constructor, you need to escape the backslash, like so: new RegExp("^[\\w]+$"), which will create the regex you want.

There is a way to avoid that, using the shorthand notation provided by JavaScript: var regex = /^[\w]+$/; which does not need any extra escaping.

like image 160
fresskoma Avatar answered Mar 04 '26 10:03

fresskoma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!