0

Trying to validate if the user has entered a name starting with a letter, is at least 8 characters long, and has at least one number in it. See the code below:-

The first two conditions I have been able to make work, its validating whether or not there's a number within. I have tried to run a function all by itself with just the number validation in it but I cant seem to get it to work. this is my latest attempt to make it work, any help would be greatly appreciated, keep in mind I am a first year student :)

function nameVerify() {

    var char1;
    var char2;
    var index;
    var NL = "\n";
    var valid = false;


    char1 = useNam.substr(0, 1);
    char1 = char1.toUpperCase();
    char2 = useNam.substr(1);

    for (index = 1; index <=useNam.length; index++){        
    while (!valid) {

    if ((char1 <"A" || char1 >"Z") || (useNam.length <8) && (char2 >=0 || char2 <=9)){
        alert("alert 1");
        useNam = prompt("prompt 2");
        char1 = useNam.substr(0, 1);
        char1 = char1.toUpperCase();
        char2 = useNam.substr(1);           


        }

    else {
        valid = true;
        alert("Congragulations, you entered it correctly");
    }
    }
    }}      

var useNam;

useNam = prompt("prompt 1");
result = nameVerify(useNam);
4
  • It would be better to use regex for this type of validation... Commented Nov 11, 2014 at 20:20
  • It's probably easier than you think -> jsfiddle.net/adeneo/pwnnct8d Commented Nov 11, 2014 at 20:22
  • Possible duplicate stackoverflow.com/questions/17899107/… Commented Nov 11, 2014 at 20:26
  • Thanks for all the help guys :). I'll do my best to apply one of these to my code, much appreciated :) Commented Nov 11, 2014 at 22:22

2 Answers 2

2
/**
 * @param {string} str name to test
 * @return {boolean} true if str is valid
 */
function isValidName(str) {
  return /^[a-zA-Z][a-zA-Z0-9]{7,}$/.test(str) && /\d/.test(str)
}

/^[a-zA-Z][a-zA-Z0-9]{7,}$/ tests that it starts with a letter, is at least 8 characters long, and all characters are letters or numbers. /\d/ tests that it contains at least 1 number. See MDN's RegExp documentation for reference in particular about the special characters and the x{n,} syntax described there. If you allow underscores too then you could use /^[a-zA-Z]\w{7,}$/ for the first test.

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

Comments

0

Try this

valid = myString.match(/\d/).length > 0

This is a regex and will return the first number it matches or an empty array otherwise

Comments

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.