开发者

Why this JavaScript RegExp results in dual answer?

Look at this simple HTML input tag:

<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex' 
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />

<p id='log'></p>

Now imagine that we want to validate this field, using this function:

var log = $('#log');
function validateRegex(field) {
    var pattern = field.attr('data-validation-regex-pattern');
    log.append(pattern + '<br />');
    if (pattern && pattern != '') {
        var isValid = new RegExp(pattern).test(field.val().trim());
        if (!isValid) {
            log.append('n开发者_StackOverflow中文版ot valid<br />');
        }
        else {
            log.text('valid<br />');
        }
    }
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());

Now, if you look at the log, you see that this line returns false:

var isValid = new RegExp(pattern).test(field.val().trim());

However, this line of code returns true:

new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());

In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.

Why? What's wrong here?

To see it in action, look at this fiddle.


Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:

data-validation-regex-pattern='^\+\d{2}\.\d{10}$'

Will work just fine:

Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/


\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.

Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).

To get your code work, replace double slashes (\\) in your HTML by a single slash.
Fiddle: http://jsfiddle.net/GRL2m/5/

Extra information:

  • In HTML, HTML entities (eg &quot;) are used to display special characters.
  • In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
  • In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜