如何在Papyrus中将CPF证件号校验规则转换为可验证的OCL约束
CPF证件号合法性校验OCL实现方案
以下OCL约束完全匹配你提供的Java校验逻辑,可直接导入Papyrus的UML模型中使用:
约束代码
-- 替换为你UML模型中对应类的名称 context Person inv validCPF: -- 第一步:移除所有标点符号,提取纯数字串 let cleanedCpf: String = self.cpf.replaceAll('[./-]', '') in -- 校验1:纯数字串长度必须为11位 cleanedCpf.size() = 11 and -- 校验2:排除前9位数字完全相同的无效号码 not cleanedCpf.substring(1,9).characters()->forAll(c | c = cleanedCpf.at(1)) and -- 转换为整数序列,方便后续计算 let numSeq: Sequence(Integer) = cleanedCpf.characters()->collect(char | char.toInteger()) in -- 计算第一个校验位 let sum1: Integer = Sequence{10,9,8,7,6,5,4,3,2}->iterate( weight: Integer; sum: Integer = 0 | sum + numSeq->at(Sequence{10,9,8,7,6,5,4,3,2}->indexOf(weight)) * weight ) in let check1: Integer = if sum1.mod(11) < 2 then 0 else 11 - sum1.mod(11) endif in -- 计算第二个校验位 let sum2: Integer = Sequence{11,10,9,8,7,6,5,4,3,2}->iterate( weight: Integer; sum: Integer = 0 | sum + numSeq->at(Sequence{11,10,9,8,7,6,5,4,3,2}->indexOf(weight)) * weight ) in let check2: Integer = if sum2.mod(11) < 2 then 0 else 11 - sum2.mod(11) endif in -- 校验位匹配验证 numSeq->at(10) = check1 and numSeq->at(11) = check2
使用说明
- 将代码开头
context后的Person替换为你的UML类实际名称 - 将
self.cpf中的cpf替换为你类中存储CPF证件号的属性名称 - 约束可以直接粘贴到Papyrus的类约束OCL编辑框中生效
内容的提问来源于stack exchange,提问作者Adalberto J. Brasaca
相关产品推荐
相关产品推荐

