1

I'm working on a validation function for html input tags. I've the string of the value of the particular input and the string containing the allowed characters.

var allowed = 'abcdefghijklmnopqrstuvwxyz"; var value = element.value; 

I'd like to write a function to determine if the value contains character only from the allowed string. I'm looking for a straight-forward and simple solution. Any ideas?

1
  • 5
    2 words: Regular Expressions. Match any pattern you can imagine. Commented Jun 27, 2013 at 9:07

3 Answers 3

13

Yes you can use regex

function alphanumeric(inputtxt) { var letters = /^[a-z]+$/; //if you want upper and numbers too //letters = /^[A-Za-z0-9]+$/; //if you only want some letters // letters = /^[azertyuiop]+$/; if(inputtxt.value.match(letters)) { alert('Your registration number have accepted : you can try another'); document.form1.text1.focus(); return true; } else { alert('Please input alphanumeric characters only'); return false; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

the allowed string can be anything (e.g. 'aeiou', etc) and is a parameter of my validate(allowed, value) function, thus I wouldn't like to use regex in this way. Could you please give me a regular expression based on the string. So I would use regex if I could make a regex of the string...
yes you can just have 'aeiou' using this regex: /^[aeiou]+$/ and you can export your string in your regex var string = "aeiou"; var reg = /^[+string+]$/
0

Use below function.

function isChar(str) { return /^[a-zA-Z]+$/.test(str); } var allowed = 'abcdefghijklmnopqrstuvwxyz'; if(isChar(allowed )){ alert('a-z cool :)'); }else{ alert('Enter only Char between a-z'); } 

Demo Link

2 Comments

Please see my comment above on @ant's anwser.
@gen check new demo jsfiddle.net/xmDNb/4. I don't think result can achieve without add Regx in allowed variable.
0

Here is an answer without the use of regex

function allLetter(inputtxt) { var inputtxt_low = inputtxt.toLowerCase(); inputtxt_low = inputtxt_low.split(''); var alpha_arr = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; var count; for(count = 0; count < inputtxt_low.length; count++) { if(alpha_arr.indexOf(inputtxt_low[count]) == -1) { inputtxt= ''; break; } } return inputtxt; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.