当前位置:编程学习 > JS >>

js正则表达式验证各类需求(整数,实数,小数,时间,URL等)

function validateNum(val){//验证整数
var patten = /^-?\d+$/;
return patten.test(val);
 }
function validateRealNum(val){//验证实数

 var patten = /^-?\d+\.?\d*$/;

 return patten.test(val);

  }

function validateNum(val){//验证小数,保留一位小数点

 var patten = /^-?\d+\.?\d{0,1}$/;

 return patten.test(val);

  }

 
 function validateFloat(val){//验证小数
var patten = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
return patten.test(val);
 }
 
 function validateNumOrLetter(val){//只能输入数字和字母
        var patten = /^[A-Za-z0-9]+$/;
        return patten.test(val);
 }
 
 function validateColor(val){//验证颜色
var patten =  /^#[0-9a-fA-F]{6}$/;
return patten.test(val);
 }
 
 function validateUrl(val){ //验证URL
var patten = /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
return patten.test(val);
 }
 
 function validateNull(val){//验证空
return val.replace(/\s+/g, "").length==0;
 }
 
 function validateDate(val){//验证时间2010-10-10
var patten = /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/;
return patten.test(val);
 }
 
 function validateNumLetterLine(val){//只能输入数字、字母、下划线
    var patten =  /^[a-zA-Z0-9_]{1,}$/;
return patten.test(val);
 }


作者:uohzoaix
补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,