3

i want to get two msgs when user type special character like m@rk @l@n with the help of charCodeAt();

my code gives an repeated answer if i enter normal text or if i enter spec char it gives my both condition true

var username = prompt("Enter Username");
var boolean = true;

for(var i=0;i<username.length;i++){

  if(username[i].charCodeAt()==33 || username[i].charCodeAt()==44 || username[i].charCodeAt()==46 || username[i].charCodeAt()==64){
        document.write("Wrong input: "+username);
        boolean=true;
        break;
  }
  else{
       document.write("correct input "+username);
  }
}
Epyc Dev
  • 282
  • 2
  • 9
  • 1
    Possible duplicate of [How to tell if a string contains a certain character in JavaScript?](https://stackoverflow.com/questions/4444477/how-to-tell-if-a-string-contains-a-certain-character-in-javascript) – Heretic Monkey Jan 31 '19 at 17:10
  • I would avoid using `boolean` as a variable name since it's a future reserved keyword from an older ECMAScript spec: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Future_reserved_keywords – Tom O. Jan 31 '19 at 17:11

1 Answers1

0

Move document.write outside of the loop:

var username = prompt("Enter Username");
    var valid = true;
    
    for(var i=0;i<username.length;i++){
    
      if(username[i].charCodeAt()==33 || username[i].charCodeAt()==44 || username[i].charCodeAt()==46 || username[i].charCodeAt()==64){
            valid=false;
            break;
      }
    }
    document.write((valid?"Correct input ":"Wrong input ")+username);
FZs
  • 16,581
  • 13
  • 41
  • 50
  • not working properly .. when i enter special character it will show me a message "Correct input" ... but this input container spec char :| – Epyc Dev Jan 31 '19 at 17:17
  • @NoobDev Which special character? I tried with `@` (as it is in your example), and it is working. – FZs Jan 31 '19 at 17:20