简体   繁体   中英

Restrict user when he enters * character in text field in c#

Is there any way to restrict user from entering * key in text field.

I have textfield where * is not allowed, so how can I explicitly disable that * key when user enter in the particular text field.

Thanks.

Use Javascript for restricting * on keypress.

Then find the ASCII keycode of * on keypress and restrict it. And ASCII keycode for * is 42.

JS

<script type="text/javascript">
    function IsAsterik(e) {            
        var keyCode = e.which ? e.which : e.keyCode
        var ret = (keyCode != 42)
        document.getElementById("error").style.display = ret ? "none" : "inline";
        return ret;
    }
</script>

Textbox

<input type="text" id="text1" runat="server" onkeypress="return IsAsterik(event);" 
        ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* not allowed</span>

Find a demo here

In C# on textbox key up event add this code

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
     string val = textBox1.Text;
     if(val.IndexOf('*')>-1)
     {
         textBox1.Text = val.Substring(0, val.Length - 1);
         if (val.Length>0)
            textBox1.SelectionStart = val.Length - 1;
          return;
     }
}

Happy Coding. :)

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