objective c - Regular expression for 10digit phonenumber in iOS -
i'm trying write regular expression match 10 digit number without other characters. eg. 2345678901
the first digit should between 2-9 while rest 9 digits can any
i have tried writing different regular expressions none worked.
nsstring *newstring = [textfield.text stringbyreplacingcharactersinrange:range withstring:string];
//^([0-9]+)?(([0-9]{9})?)?$ (([2-9]{1})?)?(([0-9]{8,9})?)? nsstring *expression = [nsstring stringwithformat:@"^(([2-9]{1})?)?(([0-9]{8,9})?)?$"]; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:expression options:nsregularexpressioncaseinsensitive error:nil]; nsuinteger numberofmatches = [regex numberofmatchesinstring:newstring options:0 range:nsmakerange(0, [newstring length])]; if (numberofmatches == 0) { return no; } return yes;
`
thanks help.
a straightforward regex match need is
^[2-9][0-9]{9}$
it matches first digit in 2..9 range, , other 9 digits in 0..9 range, ten digits in total.
note expression suitable validating entire string, not partial one. cannot use in textfield:shouldchangecharactersinrange:replacementstring:
validate digits become available.
it's not idea validate format of input it's being entered anyway, because users may choose enter phone's digits in order moving cursor right position before type. instead, should set keyboardtype
property of uitextfield
uikeyboardtypedecimalpad
, , let users type many digits want. don't limit input until tell done: may want paste data from, say, notepad, , erase separators, or enter few digits @ end before deleting section @ front of input.
instead, should use above expression in textfieldshouldendediting:
method. when regex matches, return yes
; otherwise, return no
, , give users visual feedback indicate number needs changed. read discussion section of textfieldshouldendediting:
method in uitextfielddelegate
documentation.
Comments
Post a Comment