Reputation: 63
Im trying to finish up an assignment; here's what Im stuck at:
User input can only contain the following allowed characters
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
Upvotes: 0
Views: 54
Reputation: 1597
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');
Upvotes: 1
Reputation: 2068
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.
Upvotes: 0