0

Im trying to finish up an assignment; here's what Im stuck at:

User input can only contain the following allowed characters

  • alphabetic characters lower case (a-z) upper case (A-Z)
  • apostrophe (‘)
  • hyphen (-)
  • Must have at least 1 alphabetic characters (a-z) (A-Z)

Note: You cannot make use of Reg Ex.

I can't really see another way of doing this without use of Reg Ex; Here what I've done so far...

function validate_name() {
   var name = document.getElementById("name").value;
   name = name.trim();
   for (i = 0;i < name.lenght; i++) {
      if (name.charAt(i) == a...I don't know what I'm doing
1
  • Any specific reason why RegEx cannot be used ? Commented Aug 17, 2015 at 5:56

2 Answers 2

1

You can do something like that:

var str = prompt('Enter input:');
var alphaExist = false;
var valid = true;
for (var i = 0; i < str.length; i++) {
    if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'-".indexOf(str.charAt(i)) == -1) {
        valid = false;
    }
    if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(str.charAt(i)) > -1) {
        alphaExist = true;
    }
}
alert(valid && alphaExist ? 'Valid' : 'Invalid');

http://jsfiddle.net/4wwod65h/

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

Comments

0

Have a look at the keycode list at: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Do not use

document.getElementById("name").value;

Rather parse an event triggered by keystrokes. You have a nice example of how to use this on MDN page: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

So combine the keycode list and the keyboard event to filter the keycodes you are interested in.

Hint: You are able to use a range as keycodes are bunch of numbers.

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.