0

I have the following piece of code (which was given to me) to check a 'username' field 10 digits. The field must be exactly 10 digits to continue. It must have no letters or special characters in it -- just numbers. Can someone fix this snippet so that it works right? Currently, it is letting everything pass -- no matter if it's text, numbers, short, long... whatever. Here's the code:

function checkUsername() {
  var exp = /^\d{10}$/;
  if (entered.length(exp) >10 && entered.length(exp) <=9) {
    alert("Username is not in the proper format.  You are an idiot.");
    return false;
  }
  return true;
}
3
  • It can't be both greater than 10 and less than or equal to 9. You want an "or" (||) not an "and" (&&). So maybe a little less with the idiot remarks. :) Commented Oct 23, 2013 at 20:39
  • What is entered? Where is is declared? Commented Oct 23, 2013 at 20:40
  • 1
    Uh. I assume that entered is meant to be a global variable holding the username? Should be passed in as an argument. In any case, what is entered.length(regex) meant to do? That is gibberish. Commented Oct 23, 2013 at 20:41

2 Answers 2

2

The regex test will return either true or false, it will not return the length of the string.

var exp = /^\d{10}$/;
if(exp.test(entered))
{
  // test passed, go through
}

And don't call your users idiots, users make mistakes ;) that's to be expected.

Sign up to request clarification or add additional context in comments.

1 Comment

That 'idiots' part was me just having fun with testing. It didn't go into production like that.
0

hmn its a guess but i think this should work, if any character in regex matches with entered(make sure this variable exists) or entered is smaller euqal 9, you´re an idiot

function checkUsername() {
  var exp = /[^\d.]/g;

  if (entered.match(exp) || entered.length <=9) {
    alert("Username is not in the proper format.  You are an idiot.");
  return false;
}
  return true;
}

4 Comments

The length check seems redundant now.
how do you mean? if there is an illegal character inside it will return false anyway, if theres no illegal character inside then it wil only return false if length <= 9
The regexp can't be true if the string is anything other than 10 digits in length, there's no point in the length check once you've already checked the length.
Nothing seems to be working (meaning: it is allowing any answer through). Help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.