John Setter
John Setter

Reputation: 175

RegEx JavaScript issues

I have an external JS file to validate a form. It all seems to be working. However I added in a regex to validate the password field. As soon as I did this and reloaded the page, none of my previous validation works.. Even with an empty form it submits when it shouldn't. Ive tested it and when I include the variable

var chk_name = ^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$;

It won't play nice and it submits. But as soon as I take this var out, it starts working and checking there are characters in the fields again. I've tried putting this var in the function, and also outside the function but in both situations its stopping the page from validating properly. Ill give some examples:

This works with no regex:

function validation() {
    var x=document.forms[0]["firstname"].value;
        if (x==null || x=="") {
            alert("First name must be filled out");
            return false;
        }

This doesn't work (ie the form is submitted even with no fields filled out)

var chk_name = ^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$;

function validation() {
    var x=document.forms[0]["firstname"].value;
        if (x==null || x=="") {
            alert("First name must be filled out");
            return false;
        }
var x=document.forms[0]["password"].value;
        if(x==null || x==""){
            alert("Choose a password at least 6 characters long including 1 upper case letter, 1 lower case letter and 1 number");
            return false;
        } else if(!chk_name.test(x)){
            alert("Choose a password at least 6 characters long including 1 upper case letter, 1 lower case letter and 1 number");
            return false;
        }

This also doesn't work:

function validation() {
    var x=document.forms[0]["firstname"].value;
        if (x==null || x=="") {
            alert("First name must be filled out");
            return false;
        }
var x=document.forms[0]["password"].value;
var chk_name = ^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$;
        if(x==null || x==""){
            alert("Choose a password at least 6 characters long including 1 upper case letter, 1 lower case letter and 1 number");
            return false;
        } else if(!chk_name.test(x)){
            alert("Choose a password at least 6 characters long including 1 upper case letter, 1 lower case letter and 1 number");
            return false;
        }

Upvotes: 0

Views: 37

Answers (1)

Amit Joki
Amit Joki

Reputation: 59292

var chk_name = ^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$;

should be:

var chk_name = /^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$/;

The syntax for literal regex is:

/pattern/flags

You can also use RegExp constructor:

new RegExp("pattern","flags");

Upvotes: 2

Related Questions