-2

In our application a user is prompted to enter a nickname to be connected to the conversation, but our backend server only accepts nicknames that:

  1. Don't start with a number.
  2. Don't contain spaces.

How can I replace the users input as he is choosing a nickname if it contains either of the above?

Jack
  • 515
  • 1
  • 5
  • 17
  • @depperm I have tried putting a notice on the page asking users not to include either but that doesn't seem to work :-) – Jack Jun 25 '15 at 16:30
  • possible duplicate of [how do i block or restrict special characters from input fields with jquery?](http://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery) – depperm Jun 25 '15 at 16:30
  • Have you tried regex? – JordyvD Jun 25 '15 at 16:32
  • You probably shouldn't replace the user's input, but ask them to re-input when there are bad characters. – pabrams Jun 25 '15 at 16:33
  • @pabrams i understand what you want and it's odd behavior but that's what op wanted, i'd personally do replace it but upon user typing wrong character i'd do animation at the bottom in fiddle to inform what's wrong. – Muhammad Umer Jun 25 '15 at 16:44
  • @pbrams i add animation to make ui better http://jsfiddle.net/wsywyk5L/1/ – Muhammad Umer Jun 25 '15 at 18:00

2 Answers2

2

This automatically replaces the user input to match the rules..

http://jsfiddle.net/wsywyk5L/

var i = document.getElementById("username");

i.addEventListener('input',function(){
    i.value = i.value.replace(/^\d|\W/g,'');
});
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
1

Don't start with a number.

!isNaN(parseInt(username.substr(0, 1), 10))

Don't contain spaces.

username.indexOf(' ') == -1
Richard
  • 2,840
  • 3
  • 25
  • 37