1

How can I validate the following textarea using a pure Javascript not Jquery? Can anyone help me please.

<script>
function val()
{
    // 1. only allowed alphanumeric characters, dash(-), comma(,) and no space
    // 2. alert if person is trying to input not allowed chars as in 1.
} 
</script>

<form>  
    <textarea name="pt_text" rows="8" cols="8" class="input" onkeydown="return val();"></textarea>
</form>
5
  • 2
    Did you google the regular expression for your need? Commented Mar 26, 2014 at 14:21
  • 1
    Just a suggestion for point 2. When you say alert, please don't use an actual alert box. Commented Mar 26, 2014 at 14:22
  • 1
    Why don't you want to use jQuery? Commented Mar 26, 2014 at 14:23
  • 1
    onkeydown isnt really a good for validating stuffs.. what if someone copy pastes with mouse o_O Commented Mar 26, 2014 at 14:32
  • @Deja Vu, because it's clearly a homework/test question. ;) Commented Mar 26, 2014 at 14:32

2 Answers 2

1

Try something like:

document.querySelector('.input').onkeypress = function validate(e) {
    if (String.fromCharCode(e.keyCode).match(/[\w,-]/) == null) {
        alert('not allowed');
        e.preventDefault();
    }
};

DEMO

Edit: As pointed out by tenub, \w also allows _, so modify the regex to: /[A-Za-z0-9,-]/

DEMO

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

Comments

0

This regex will match only valid strings:

/^[\w,-]*$/

Use + instead of * if you don't allow empty strings.

1 Comment

Ah, right. /^[-\w,-[_]]*$/ if character class subtraction is supported, otherwise /^[a-zA-Z0-9,-]*$/. (Probably use the last one anyway for readability.)

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.