0

I have a Javascript function like this:

function validateSessionName() {
  var session_name = document.getElementById('session_name').value;
  var submitButton = document.getElementById('submit');
  document.getElementById('session_error').innerHTML='';
  submitButton.removeAttribute('disabled');
  var filter = /^[A-Za-z0-9]+$/;
  if (filter.test(session_name)){
    return true;
  } else {
    document.getElementById('session_error').innerHTML="Invalid Session Name!";
    submitButton.setAttribute('disabled', 'disabled');
  }
}

This validates that only numbers and alphanumerical characters are entered into the form. However, there might be a case when a session name can consist of !@$#$#(%*. All these characters are available on the keyboard. I don't want my application to accept these weird characters: 工具, which make my application crash. How can I do that? Thanks.

dda
  • 6,030
  • 2
  • 25
  • 34
pynovice
  • 7,424
  • 25
  • 69
  • 109
  • 5
    A more useful strategy would be to make your application NOT crash when it gets unexpected characters... – dda Jun 11 '13 at 05:18
  • 1
    If user input is making your application crash, you should fix your application, not the input. – Cameron Jun 11 '13 at 05:18

2 Answers2

2

It depends what you mean by "English keyboard" and "weird characters".

You're probably thinking of limiting your input to ASCII characters, but even then you can get "weird" characters such as null, and a host of control characters. Perhaps limiting the characters to the ASCII range [32, 126] is what you're after? (Those are all printable characters that can be input on a US keyboard.)

/^[\x20-\x7E]+$/

The characters that match that regex are (note the leading space):

  ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ 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 [ \ ] ^ _ ` 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 { | } ~
Cameron
  • 96,106
  • 25
  • 196
  • 225
0

https://blogs.oracle.com/shankar/entry/how_to_handle_utf_8

How to remove invalid UTF-8 characters from a JavaScript string?

Or just google something to this like

Community
  • 1
  • 1
nsawaya
  • 622
  • 5
  • 8