How to translate ruby regex to javascript? - (?i-mx:..) and Rails 3.0.3

前端 未结 3 1354
自闭症患者
自闭症患者 2021-01-01 18:34

Im using validates_format_of method to check email format:

validates_format_of :email, :with => /^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i
相关标签:
3条回答
  • 2021-01-01 18:45

    Ruby and JavaScript regular expressions are parsed and executed by different engines with different capabilities. Because of this, Ruby and JavaScript regular expressions have small, subtle differences which are slightly incompatible. If you are mindful that they don't directly translate, you can still represent simple Ruby regular expressions in JavaScript.

    Here's what client side validations does:

    class Regexp
      def to_javascript
        Regexp.new(inspect.sub('\\A','^').sub('\\Z','$').sub('\\z','$').sub(/^\//,'').sub(/\/[a-z]*$/,'').gsub(/\(\?#.+\)/, '').gsub(/\(\?-\w+:/,'('), self.options).inspect
      end
    end
    

    The recent addition of the routes inspector to rails takes a similar approach, perhaps even better as it avoids monkey patching:

    def json_regexp(regexp)
      str = regexp.inspect.
            sub('\\A' , '^').
            sub('\\Z' , '$').
            sub('\\z' , '$').
            sub(/^\// , '').
            sub(/\/[a-z]*$/ , '').
            gsub(/\(\?#.+\)/ , '').
            gsub(/\(\?-\w+:/ , '(').
            gsub(/\s/ , '')
      Regexp.new(str).source
    end
    

    Then to insert these into your javascript code, use something like:

    var regexp = #{/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.to_javascript};
    
    0 讨论(0)
  • 2021-01-01 18:53

    I've written a small gem that translates Ruby regexes to JavaScript:

    https://github.com/janosch-x/js_regex

    It can handle more cases than the gsub approach, and includes warnings if any incompatibilities remain.

    Note that, whatever you do, not all Ruby regexes can be fully translated to JS, because Ruby's regex engine has a lot of features that JavaScript's doesn't have.

    0 讨论(0)
  • 2021-01-01 19:02

    The reason is that you are converting your regular expression using .to_s instead of .inspect. What you need to do in your view is use .inspect to get the proper format. Here is some sample code that should explain the issue:

    email = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
    email.to_s #"(?i-mx:^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$)"
    email.inspect #"/^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$/i"
    

    so, in your javascript view do something like this to get the actual string representation you want:

    <%= email.inspect %>
    
    0 讨论(0)
提交回复
热议问题