ROYDENSTORM
ROYDENSTORM

Reputation: 11

How to validate input fields ensuring specific string patterns in Javascript

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);

Upvotes: 0

Views: 210

Answers (2)

ryanve
ryanve

Reputation: 52501

/**
 * @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.

Upvotes: 2

Simon H
Simon H

Reputation: 21005

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

Upvotes: 0

Related Questions