Is it possible to validate IMEI Number?

后端 未结 5 917
时光取名叫无心
时光取名叫无心 2021-02-09 09:40

For a mobile shop application, I need to validate an IMEI number. I know how to validate based on input length, but is their any other mechanism for validating the input number?

5条回答
  •  借酒劲吻你
    2021-02-09 10:01

    IMEI can start with 0 digit. This is why the function input is string. Thanks for the method @KarlNicol

    Golang

    func IsValid(imei string) bool {
        digits := strings.Split(imei, "")
    
        numOfDigits := len(digits)
    
        if numOfDigits != 15 {
            return false
        }
    
        checkingDigit, err := strconv.ParseInt(digits[numOfDigits-1], 10, 8)
        if err != nil {
            return false
        }
    
        checkSum := int64(0)
        for i := 0; i < numOfDigits-1; i++ { // we dont need the last one
            convertedDigit := ""
    
            if (i+1)%2 == 0 {
                d, err := strconv.ParseInt(digits[i], 10, 8)
                if err != nil {
                    return false
                }
                convertedDigit = strconv.FormatInt(2*d, 10)
            } else {
                convertedDigit = digits[i]
            }
    
            convertedDigits := strings.Split(convertedDigit, "")
    
            for _, c := range convertedDigits {
                d, err := strconv.ParseInt(c, 10, 8)
                if err != nil {
                    return false
                }
                checkSum = checkSum + d
            }
    
        }
    
        if (checkSum+checkingDigit)%10 != 0 {
            return false
        }
    
        return true
    }
    

提交回复
热议问题