常用数字处理格式校验
1、前端校验
1.1 要求为数字类型(不限位数与正负)
input输入框添加 type=“number”
<el-input type="number"/>
当type=number时,仍然可以输入字母e或E。解决方法是:给type=number的输入框添加一个正则表达式:
<el-input type="number" onKeypress="return(/[\d\.]/.test(String.fromCharCode(event.keyCode)))" />
1.2 要求为正整数(如学时、人数等)
<el-input v-model="form.trainHour" placeholder="请输入" onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
1.3 要求为大于零且保留两位小数(如温度、金额等)
<el-input v-model="form.budget" placeholder="请输入" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"></el-input>
2、后端校验
2.1 判断为正整数
String vlaue = "12356";
if(StringUtils.isNumeric(vlaue)){
//如果为正整数,返回true;
}
2.2 判断为正数
public static void main(String[] args) {
String reg = "^[0-9]+(.[0-9]+)?$";
String s1 = "100.43";
String s2 = "month";
System.out.println(s1.matches(reg)); // true
System.out.println(s2.matches(reg)); // false
}
2.3 判断数字类型
public static void main(String[] args) {
String reg = "^-?[0-9]+(.[0-9]+)?$";
String s1 = "10000";
String s2 = "100.43";
String s3 = "-100";
String s4 = "month";
String s5 = "1023.89";
System.out.println(s1.matches(reg));// true
System.out.println(s2.matches(reg));// true
System.out.println(s3.matches(reg));// true
System.out.println(s4.matches(reg)); // false
System.out.println(s5.matches(reg));// true
}