Forum: Ruby on Rails validation help

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Newb N. (Guest)
on 2009-06-09 09:02
i use this code to validate the phone field.it should have only numbers.
but it also accepts alphapets with numbers.it should not accept other
than numkbers
below is my code i use.
errors.add(:phone_code, "*please enter valid phone number") unless
self.phone_code =~/[0-9]/

is there any fault in my regular expression ...
any helps pls..
Colin L. (Guest)
on 2009-06-09 13:53
(Received via mailing list)
2009/6/9 Newb N. <removed_email_address@domain.invalid>:
>
> i use this code to validate the phone field.it should have only numbers.
> but it also accepts alphapets with numbers.it should not accept other
> than numkbers
> below is my code i use.
> errors.add(:phone_code, "*please enter valid phone number") unless
> self.phone_code =~/[0-9]/

That will match if there is at least one number in the string. I think
you need something like
/\A[0-9]*\z/
or
/\A\d*\z/

or possibly even better you could use something like
validates_numericality_of :phone_code, :only_integer => true,
:greater_than => 0
Though I think this would allow a leading + character.

Colin
Frederick C. (Guest)
on 2009-06-09 14:00
(Received via mailing list)
On Jun 9, 10:53 am, Colin L. <removed_email_address@domain.invalid> wrote:
>
> That will match if there is at least one number in the string. I think
> you need something like
> /\A[0-9]*\z/
> or
> /\A\d*\z/

if you are going to use a regexp you might as well use
validates_format_of rather than doing it yourself

Fred
Gerardo Gonzalez C. (Guest)
on 2009-06-09 19:04
(Received via mailing list)
A Simple Example using RegExp:

<html>
<head>
<script language='javascript'>
function CheckThis(obj) {
    var strRegExp = /^[0-9]*$/;
    if(!strRegExp.test(obj.value))
        obj.value = '';
}
</script>
</head>
<body>
<p>Insert your data number here:</p>
<input type='text' id='test' size='10' value=''
onkeyup='CheckThis(this);'/>
</body>
</html>

I don't know if this can help you, i hope.
See more: http://evolt.org/regexp_in_javascript.


On Tue, Jun 9, 2009 at 12:02 AM, Newb N.
<removed_email_address@domain.invalid
This topic is locked and can not be replied to.