Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Im using validates_format_of method to check email format:

validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

also Im using livevalidation plugin to validate forms, so in my code Im getting:

(?i-mx:^([^@\\s]+)@((?:[-a-z0-9]+\\.)+[a-z]{2,})$)

Javascript cant read this regex. How or where I can change this regex to be as original:

/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

?

like image 913
jacek2012 Avatar asked Jan 31 '11 18:01

jacek2012


1 Answers

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};
like image 129
sj26 Avatar answered Oct 02 '22 07:10

sj26