简体   繁体   中英

Regex always returning either always true or always false regardless of valid test value

I am trying to validate a form field using Regex. The field should contain 5 numbers (ie 12345 = valid, 1234a = invalid, 123456 = invalid), that is it. no more, no less. The problem is with different regex formats, the .test() method either always returns true, or always returns false. It never works for correct values and fails for incorrect values. All regex testers test the regex successfully for JavaScript but when I add it to my page (WordPress), I get these issues. I read up about the /g field should be removed and tried all that. still no luck.

HTML:

<form name="newform" action="Create.php"  onsubmit="return validateForm()" method="POST" >
    Code <br/><br/><input id="code" class="form-control" type="text" value="" name="code"  onkeypress="CodeStyleRefresh()" />
    <button type="submit" id="submit" name="submit">Create</button>
</form>

JavaScript:

<script type="text/javascript">
function validateForm(){
    var CodePattern = new RegExp(/\b\d{5}\b/);

    if(CodePattern.test(document.forms["newform"]["code"].value) == true)
    {
        return true;
}
    else
    {
        return false;
    }
}
function CodeStyleRefresh(){
    document.getElementById("code").setAttribute("style", "background-color: #ffffff;");
}
</script>

Some other ways I have tried to specify the expression:

var CodePattern = new RegExp(/\b\d{5}\b/);
var CodePattern = new RegExp('/\b\d{5}\b/');
var CodePattern = /\b\d{5}\b/;
var CodePattern = '/\b\d{5}\b/';
var CodePattern = \b\d{5}\b;
var CodePattern = '\b\d{5}\b';

This is my first time ever touching regex and I am fairly new to the JavaScript family as well. Not having such a good time.

UPDATE:

I have gone back to basics. My JavaScript now looks as follows based on a few suggestions:

function validateForm(event)
{   
    console.log("Im running the script!");
    console.log(event.target.querySelector("[name=code]").value);

    var CodePattern = new RegExp(/\b\d{5}\b/);
    var codeVal = event.target.querySelector("[name=code]").value;

    if(CodePattern.test(codeVal) == true)
    {
        alert("Expression Passed!");
    }
    else
    {
        alert("Expression Failed!");
        return false;
    }
}

My HTML is now:

<form name="newform" onsubmit="return validateForm(event)" method="POST">
  Code
  <input id="code" class="form-control" type="text" value="" name="code" />
  <button type="submit" id="submit" name="submit">Create</button>
</form>

Still this expression is only hitting the failed state and alerts expression failed.

If it helps, I am adding the JavaScript to a WordPress page, the form is normal html on the same page. I have tried adding the JavaScript to both the header and the footer but this does not change anything. I'm starting to think I should just check if the length of the field = 5 and if I can then cast it to an int instead of using RegEx at all!

Your regex is fine. If you are only getting the error when you upload your code to your wordpress site, I'd be tempted to say that your problem is your context, perhaps you have more than one form with the same name?

Try a context aware piece of code, update your html to:

<form name="newform" onsubmit="return validateForm(event)" method="POST">
  Code
  <input id="code" class="form-control" type="text" value="" name="code" onkeypress="CodeStyleRefresh()" />
  <button type="submit" id="submit" name="submit">Create</button>
</form>

And your javascript:

function validateForm(event){
    var myRegex = new RegExp(/\b\d{5}\b/);
    //event.target holds the node element that triggered the function in our case, the Form itself
    var myValue = event.target.querySelector("[name=code]").value; //here we find the input with the name=code inside the form that triggered the event

  return myRegex.test(myValue) //return true if it passed, false if not
}

Since I cannot insert this much code in comments, I am posting an answer here to show how it all works.

 function validateForm(frm, evt) { var codeVal = frm.code.value; var CodePattern = /\\b\\d{5}\\b/; // comment below line after testing evt.preventDefault(); if(CodePattern.test(codeVal) == true) { console.log("Expression Passed!"); return true; } else { console.log("Expression Failed!"); return false; } } 
 <form name="newform" onsubmit="return validateForm(this, event)" method="POST"> Code <br/><br/> <input id="code" type="text" value="abc 12345 foo bar" name="code" /> <input type="submit" id="submit" name="submit" value="Create" /> </form> 

Thank you for all the suggestions. I have learnt a few things by looking at them all and I have made a few changes.

I could not however get the regex to work properly in wordpress. I was forced to create a longwinded, dirtier solution to this. I will continue to look at possible solutions and test on other wordpress sites, but for now, this is the code I am using to validate the field:

  function validateForm(frm, evt) { var codeVal = frm.code.value; console.log("Code Value: " + String(codeVal)); // comment below line after testing evt.preventDefault(); var lenPass = false; var strlen = codeVal.length; if(strlen == 5) { lenPass = true; } if(lenPass) { var c1 = Number.isNaN(Number(codeVal.charAt(0))); var c2 = Number.isNaN(Number(codeVal.charAt(1))); var c3 = Number.isNaN(Number(codeVal.charAt(2))); var c4 = Number.isNaN(Number(codeVal.charAt(3))); var c5 = Number.isNaN(Number(codeVal.charAt(4))); console.log(c1); console.log(c2); console.log(c3); console.log(c4); console.log(c5); var pass = true; if(c1) { pass = false; } if(c2) { pass = false; } if(c3) { pass = false; } if(c4) { pass = false; } if(c5) { pass = false; } if(pass) { alert("Expression Stage 2 Passed!"); return true; } else { alert("Expression Stage 2 Failed!"); return false; } } else { alert("Expression Stage 1 Failed!"); return false; } } 
 <html> <head> </head> <body> <form name="newform" onsubmit="return validateForm(this, event)" method="POST"> Code <br/><br/> <input id="code" type="text" value="" name="code" /> <input type="submit" id="submit" name="submit" value="Create" /> </form> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM