简体   繁体   中英

Prevent user from inputing dollar sign ($)

I would like to use regular expressions to prevent the dollar "$" symbol from being entered into the form. I have attempted regular expressions and can't seem to figure it out. Any assistance would be welcomed.

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    StripNonAlphabetCharacters(TextBox1)
End Sub

        Public Sub StripNonAlphabetCharacters(ByVal input As TextBox)
        ' pattern matches any character that is NOT A-Z (allows upper and lower case alphabets)
    Dim rx As New Regex("[^a-zA-Z]")
    If (rx.IsMatch(input.Text)) Then
        Dim startPosition As Integer = input.SelectionStart - 1
        input.Text = rx.Replace(input.Text, "")
        input.SelectionStart = startPosition
    End If
End Sub

Fiddle

You don't need to use regular expression to solve this problem. I feel using the onkeypress event handler of input fields is a better solution.

 var field = document.getElementsByTagName('input')[0]; field.onkeypress = function(e) { //check if the charCode of the symbol inputed is 36 (the character code of $) if (e.charCode === 36) { return false; //prevent it from being inputted into the field } }; 

Event handlers are passed an event object that provides description about the action that triggered the event. One of the useful properties of the onkeypress event is the charCode property which shows the character code of the key pressed (I believe these numbers are the ASCII representations of the characters).

Try this expression => /^([^$])+$/

    expression = /^([^$])+$/;

    if( expression.test("String Value") ){
       alert("String value has no $");
    }else{
       alert("$ found in string");
    }

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