ios 正则表达式之验证手机号、邮箱、身份证、银行卡

时间:2022-11-04 12:50:05

1、手机号

1
2
3
4
5
6
+ ( BOOL ) IsPhoneNumber:( NSString  *)number
{
     NSString  *phoneRegex1=@ "1[34578]([0-9]){9}" ;
     NSPredicate  *phoneTest1 = [ NSPredicate  predicateWithFormat:@ "SELF MATCHES %@" ,phoneRegex1];
     return   [phoneTest1 evaluateWithObject:number];
}

 2、邮箱

1
2
3
4
5
6
+ ( BOOL ) IsEmailAdress:( NSString  *)Email
{
     NSString  *emailCheck = @ "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ;
     NSPredicate  *emailTest = [ NSPredicate  predicateWithFormat:@ "SELF MATCHES%@" ,emailCheck];
     return  [emailTest evaluateWithObject:Email];
}

 3、身份证

1
2
3
4
5
6
7
8
9
+ ( BOOL ) IsIdentityCard:( NSString  *)IDCardNumber
{
     if  (IDCardNumber.length <= 0) {
         return  NO ;
     }
     NSString  *regex2 = @ "^(\\d{14}|\\d{17})(\\d|[xX])$" ;
     NSPredicate  *identityCardPredicate = [ NSPredicate  predicateWithFormat:@ "SELF MATCHES %@" ,regex2];
     return  [identityCardPredicate evaluateWithObject:IDCardNumber];
}

 4、银行卡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
+ ( BOOL ) IsBankCard:( NSString  *)cardNumber
{
     if (cardNumber.length==0)
     {
         return  NO ;
     }
     NSString  *digitsOnly = @ "" ;
     char  c;
     for  ( int  i = 0; i < cardNumber.length; i++)
     {
         c = [cardNumber characterAtIndex:i];
         if  (isdigit(c))
         {
             digitsOnly =[digitsOnly stringByAppendingFormat:@ "%c" ,c];
         }
     }
     int  sum = 0;
     int  digit = 0;
     int  addend = 0;
     BOOL  timesTwo =  false ;
     for  ( NSInteger  i = digitsOnly.length - 1; i >= 0; i--)
     {
         digit = [digitsOnly characterAtIndex:i] -  '0' ;
         if  (timesTwo)
         {
             addend = digit * 2;
             if  (addend > 9) {
                 addend -= 9;
             }
         }
         else  {
             addend = digit;
         }
         sum += addend;
         timesTwo = !timesTwo;
     }
     int  modulus = sum % 10;
     return  modulus == 0;
}