Skip to content

Instantly share code, notes, and snippets.

@kovalevsky
Created August 26, 2014 17:59
Show Gist options
  • Save kovalevsky/2773d575e0401b8e6601 to your computer and use it in GitHub Desktop.
Save kovalevsky/2773d575e0401b8e6601 to your computer and use it in GitHub Desktop.
My first jquery plugin: prevent any input except allowed by regexp
do ($ = jQuery) ->
$.fn.extend
phoneInput: (options) ->
settings = regexp: /^(\+7|8)\d{0,10}$/
settings = $.extend settings, options
getChar = (event) ->
if event.which == null # IE
return null if event.keyCode < 32 # Special chars
return String.fromCharCode event.keyCode
if event.which != 0 && event.charCode != 0 # Any browser except IE
return null if event.which < 32 # Special chars
return String.fromCharCode event.which
# Special chars here
return null
return @each () ->
@.value = '' unless settings.regexp.test @.value
@.onkeypress = (e) ->
e = e || window.event
return if e.ctrlKey || e.altKey || e.metaKey
char = getChar(event || window.event)
return unless char
value = @.value + char
@.value = value if value == '+' || settings.regexp.test(value)
false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment