Sorry that this is such a basic question. I'm a total beginner, trying to teach myself JS so I'd appreciate any advice or even if someone could recommend a good site for newbies. The books I have aren't very good and I usually end up doing things by trial and error which probably isn't a good idea :) What I'm trying to do is very simple. I'm trying to write a short piece of code that will accept an input code from a user which has to be 8 characters long and all alphabetic and upper case. Making sure there is 8 characters is fine, I've got that bit :lol: I'm trying to get my head around the For statements. I can get it to accept a code with one uppercase letter, but have had a total mind block and can't get it to accept all uppercase letters between a-z.

Any help would be greatly appreciated as it's really annoying me now. I've probably done more complicated stuff but for some reason can't figure this one out.

Dani AI

Generated

— since the length check is already working, the cleanest solution is a regular expression. pointed to regex, which is exactly the right tool for "exactly 8 uppercase letters". A compact validator:

function isValidCode(s) {
  s = (s || '').trim();
  return /^[A-Z]{8}$/.test(s);
}

For learning purposes (practice with for), the same rule can be implemented by checking each character code so the loop mechanics become clear:

function isValidCodeLoop(s) {
  if (typeof s !== 'string') return false;
  s = s.trim();
  if (s.length !== 8) return false;
  for (var i = 0; i < s.length; i++) {
    var c = s.charCodeAt(i);
    if (c < 65 || c > 90) return false; // not A-Z
  }
  return true;
}

Notes and cautions: both examples validate only ASCII A–Z. If lowercase input should be accepted and normalized, call toUpperCase() before testing (but be aware of Unicode edge cases where uppercasing can change length, e.g., German sharp s). Always trim() the input to remove accidental spaces. The regex approach is concise and preferred for production form checks; the loop approach is useful for learning how character validation works.

Further reading: MDN: Regular expressions and MDN: String.prototype.charCodeAt. — the loop example might help while learning JS basics.

Recommended Answers

All 2 Replies

Since you're learning, which is fantastic, I won't give you a complete answer. I think you should research "Regular Expressions", often referred to as "regex".

cant help bt im still new to this js also . good luck

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.