1

I have a input type URL and client want to only accept ENGLISH characters on input

Keypress and Blur function is what I have but in blur it still accept this likr inout "建築家test.com"

<input type="url" id="url" required pattern="https?://.+" placeholder="http://example.com">

    $("#url").on("keypress", function(event) {

    var englishAlphabetDigitsAndWhiteSpace = /[a-zA-Z0-9!@#$%^*_|:/.]/g;

    var key = String.fromCharCode(event.which);

    if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || englishAlphabetDigitsAndWhiteSpace.test(key)) {
        return true;
    }

    return false;
   });

$("#url").blur(function(e){
    var input = $(this).val();
    var regex = /[a-zA-Z0-9!@#$%^*_|:/.]/g; 
    if(regex.test(input)) {
      alert("OK");
    }
    else {
        alert("no Japanese allowed");
        return false;  
    }
});
Dave
  • 193
  • 1
  • 19
  • 1
    `if ([...'建築家test.com'].find(s => s.codePointAt(0) > 255)) { console.log('invalid input') }` – Brian Nov 27 '17 at 03:20
  • I will also try your answer – Dave Nov 27 '17 at 03:23
  • what iss.codePoint(0) – Dave Nov 27 '17 at 03:29
  • This returns the unicode code point of a string at the specified position. Because we only want English characters and punctuation (which all have a code point of equal to or less than 255), we can use this function to filter out any non-english strings. – Brian Nov 27 '17 at 03:33
  • This may help if you want to filter for only japanese characters: https://stackoverflow.com/questions/19899554/unicode-range-for-japanese – Brian Nov 27 '17 at 03:42
  • Thanks for your effort I will take a look – Dave Nov 27 '17 at 03:43

1 Answers1

1

Could you try with the following regex:

^([a-zA-Z0-9!@#$%^*_|:/.])*$

or that one, depending on if you accept empty string or not as valid entry.

^([a-zA-Z0-9!@#$%^*_|:/.])+$

Last but not least, if you want to check that your input is a well-formed UR, have a look at the following link:

What is the best regular expression to check if a string is a valid URL?

Allan
  • 12,117
  • 3
  • 27
  • 51
  • wow thanks can I ask you also again in comments? about input who accept japanese only? vice versa my question – Dave Nov 27 '17 at 03:28
  • You can adapt the following regex to fit your needs: `[一-龠ぁ-ゔァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+[々〆〤]+/u` https://stackoverflow.com/questions/6787716/regular-expression-for-japanese-characters and beware of the encoding UTF-8 vs Shift-JIS!!! -> this link is also quite interesting: http://www.localizingjapan.com/blog/2012/01/20/regular-expressions-for-japanese-text/ – Allan Nov 27 '17 at 03:50
  • 1
    @JohnDaveManuel Not relevant to Japanese, but remember than English *does* have characters with accent marks on them - they're just not as common. – jhpratt Nov 27 '17 at 04:23
  • can you please elaborate? – Dave Nov 27 '17 at 07:20