check a textbox for invalid characters using js and regular expressions

后端 未结 3 1831
滥情空心
滥情空心 2020-12-21 08:25

I am having a hard time figuring out how RegExp work.

I need to rewrite some ASP code into html and js, and I\'ve hit an obstacle in this part:



        
相关标签:
3条回答
  • 2020-12-21 08:43

    You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:

    ValidationExpression="^[^#%&*:<>?/{|}]+$"
    

    EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:

    new RegExp(validationExpressionGoesHere);
    
    0 讨论(0)
  • 2020-12-21 08:44

    If you want the regex to check for invalid characters in the field, you can use this.

    ^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.

    0 讨论(0)
  • 2020-12-21 08:45

    [^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).

    function regexValidator(control) {
            var val = $(control).val();
            if(val == undefined || val == '') {
    
                $(control).attr("class", "invalid");
            } 
            else if(val.match(/[^#%&*:<>?/{|}]+/)) {
                // Valid
            }
            else {
                // Invalid
            }
        }
    
    0 讨论(0)
提交回复
热议问题