简体   繁体   中英

Can anyone fix my js textarea restrict special characters space issue

Original code


<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/JavaScript">
function valid(f) {
!(/^[A-z&#209;&#241;0-9]*$/i).test(f.value)?f.value = f.value.replace(/[^A-z&#209;&#241;0-9]/ig,''):null;
} 
</script>
</head>
<body><br>
<form id="myform" action="">
<input name="mytext" type="text" onkeyup="valid(this)" onblur="valid(this)">
</form>
</body>
</html>

i prefer the code in javascript ! thanks

i can't figuerout how to let the spaces to be allowed in? anyone have an idea i tried in jquery but idk why im always getting errors same as js / i think the space bar RegExp is "" \s "" but it doesn't seem to work?

a space in regex is just " ". It seemed to work if I simply added a space in your regex

function valid(f) {
!(/^[A-z&#209;&#241;0-9 ]*$/i).test(f.value)?f.value = f.value.replace(/[^A-z&#209;&#241;0-9 ]/ig,''):null;
} 

edit: I tried \s and it seems to also work

function valid(f) {
!(/^[A-z&#209;&#241;0-9\s]*$/i).test(f.value)?f.value = f.value.replace(/[^A-z&#209;&#241;0-9\s]/ig,''):null;
}

You can just use a literal space character. That's what I'm doing here after the 0-9 :

function valid(f) {
  !(/^[A-z&#209;&#241;0-9 ]*$/i).test(f.value)?f.value = f.value.replace(/[^A-z&#209;&#241;0-9 ]/ig,''):null;
} 

I created a before and after here: https://jsfiddle.net/bzu6tg92/1/

As you can see in that example, the "after" allows the space, whereas the "before" (your code) replaces it.

So just add the space character and you should be good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM