Home Web Front-end JS Tutorial Collection of frequently used javascript verification functions_javascript skills

Collection of frequently used javascript verification functions_javascript skills

May 16, 2016 pm 07:08 PM

It is recommended that you collect the javascript verification function and use it directly when you encounter it in the future
/*
======================== ============================================

是否为空,只判断字符串 
null或0长为空,经过trim 
IsStringNull(string)
Copy after login

============================================== ======================

*/

function IsStringNull(str) { 
    if (str == null) 
        return true; 
    var trimStr = Trim(str); 
    if (trimStr.length == 0) 
        return true; 
    return false; 
}
Copy after login

/*

================================================== ================

LTrim(string):去除左边的空格
Copy after login

==================== ===============================================

*/

function LTrim(str) { 
    var whitespace = new String(" \t\n\r"); 
    var s = new String(str); 
    if (whitespace.indexOf(s.charAt(0)) != -1) { 
        var j = 0, i = s.length; 
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1) { 
            j++; 
        } 
        s = s.substring(j, i); 
    } 
    return s; 
}
Copy after login

/*

====================== ============================================

RTrim(string):去除右边的空格
Copy after login

============================================== ======================

*/ 
function RTrim(str) { 
    var whitespace = new String(" \t\n\r"); 
    var s = new String(str); 
    if (whitespace.indexOf(s.charAt(s.length - 1)) != -1) { 
        var i = s.length - 1; 
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) { 
            i--; 
        } 
        s = s.substring(0, i + 1); 
    } 
    return s; 
} 
/*
Copy after login

================ ==================================================

Trim(string):去除前后空格
Copy after login

======================================== ============================

*/ 
function Trim(str) { 
    return RTrim(LTrim(str)); 
} 
/*
Copy after login

======== ================================================== =========

IsOutOfLength(string,int):判断字符串是长度是否超出长度,中文为2个字符
Copy after login

================================ =====================================

*/ 
function IsOutOfLength(str, len) { 
    var strLength = 0; 
    for (var i = 0; i < str.length; i++) { 
        if (str.charCodeAt(i) > 256) { 
            strLength++; 
        } 
        strLength++; 
        if (strLength > len) { 
            return true; 
        } 
    } 
    return false; 
} 
/*
Copy after login

================================================== ==================

IsOutOfLength(string,int):判断字符串是长度是否超出长度,中文为3个字符
Copy after login

==================== ==============================================

*/ 
function IsOutOfLength3(str, len) { 
    var cArr = str.match(/[^\x00-\xff]/ig); 
    var len_address = str.length + (cArr == null ? 0 : cArr.length * 2); 
    if (len_address > len) 
        return true; 
    else 
        return false; 
} 
/*
Copy after login

========================================== ===========================

IsNumeric(string):判断字符串是是否为数字
Copy after login



== ================================================== ==============

*/ 
function IsNumeric(strNumber) { 
    if (strNumber.length == 0) { 
        return false; 
    } 
    return (strNumber.search(/^(-|\+)?\d+(\.\d+)?$/) != -1); 
} 
/*
Copy after login

====================== =============================================

IsInt(string,string,int or string):(测试字符串,+ or - or empty,empty or 0) 
功能:判断是否为整数、正整数、负整数、正整数+0、负整数+0
Copy after login

========================================== =========================

*/ 
function IsInt(objStr, sign, zero) { 
    var reg; 
    var bolzero; 
    if (Trim(objStr) == "") { 
        return false; 
    } 
    else { 
        objStr = objStr.toString(); 
    } 
    if ((sign == null) || (Trim(sign) == "")) { 
        sign = "+-"; 
    } 
    if ((zero == null) || (Trim(zero) == "")) { 
        bolzero = false; 
    } 
    else { 
        zero = zero.toString(); 
        if (zero == "0") { 
            bolzero = true; 
        } 
        else { 
            alert("检查是否包含0参数,只可为(空、0)"); 
        } 
    } 
    switch (sign) { 
        case "none": 
            if (!bolzero) { 
                reg = /^[0-9]*[1-9][0-9]*$/; 
            } 
            else { 
                reg = /^[0-9]*[0-9][0-9]*$/; 
            } 
            break; 
        case "+-": 
        //整数 
            reg = /(^-?|^\+?)\d+$/; 
            break; 
        case "+": 
            if (!bolzero) { 
                //正整数 
                reg = /^\+?[0-9]*[1-9][0-9]*$/; 
            } 
            else { 
                //正整数+0 
                //reg=/^\+?\d+$/; 
                reg = /^\+?[0-9]*[0-9][0-9]*$/; 
            } 
            break; 
        case "-": 
            if (!bolzero) { 
                //负整数 
                reg = /^-[0-9]*[1-9][0-9]*$/; 
            } 
            else { 
                //负整数+0 
                //reg=/^-\d+$/; 
                reg = /^-[0-9]*[0-9][0-9]*$/; 
            } 
            break; 
        default: 
            alert("检查符号参数,只可为(空、+、-)"); 
            return false; 
            break; 
    } 
    var r = objStr.match(reg); 
    if (r == null) { 
        return false; 
    } else { 
        return true; 
    } 
} 
/*
Copy after login

============== ================================================== ===

checkIsValidDate(string) 
功能:判断是否为正确的日期类型。必须为yyyy-MM-dd
Copy after login

================================ =================================

*/ 
function checkIsValidDate(str) { 
    //如果为空,则通过校验 
    if (str == "") 
        return true; 
    var pattern = /^\d{4}\/\d{1,2}\/\d{1,2}$/g; 
    if (!pattern.test(str)) 
        return false; 
    //alert("【" +str+"】1"); 
    var arrDate = str.split("/"); 
    var date = new Date(arrDate[0], (parseInt(arrDate[1], 10) - 1) + "", parseInt(arrDate[2], 10) + ""); 
    //alert("a:【" +date.getFullYear()+"】【" + date.getMonth() + "】【" + date.getDate() + "】"); 
    //alert("b:【" +arrDate[0]+"】【" + parseInt(arrDate[1],10) + "】【" + parseInt(arrDate[2],10) + "】"); 
    if (date.getFullYear() == arrDate[0] 
            && date.getMonth() == (parseInt(arrDate[1], 10) - 1) + "" 
            && date.getDate() == parseInt(arrDate[2], 10) + "") 
        return true; 
    else 
    //alert("【" +str+"】2"); 
        return false; 
} 
/*
Copy after login

====== ================================================== ===========

checkIsValidTime(string) 
功能:判断是否为正确的时间类型。必须为hh:mm:ss
Copy after login

======================== =========================================

*/ 
function checkIsValidTime(str) { 
    //如果为空,则通过校验 
    if (str == "") 
        return true; 
    var pattern = /^\d{1,2}:\d{1,2}:\d{1,2}$/g; 
    if (!pattern.test(str)) 
        return false; 
    //alert("【" +str+"】1"); 
    return true; 
} 
/*
Copy after login

================================================== ===================

CheckedCount(containForm,chkFormName):计算一个form中选中相的数目 
check表单包括radiobox和checkbox 
参数:包含check项的form,check表单的名称
Copy after login

================ ==================================================

*/ 
function CheckedCount(containForm, chkFormName) { 
    var chkCount = 0; 
    for (i = 0; i < containForm.elements.length; i++) { 
        if (containForm.elements[i].name == chkFormName) { 
            if (containForm.elements[i].type == &#39;checkbox&#39; || containForm.elements[i].type == &#39;radio&#39;) { 
                if (containForm.elements[i].checked) { 
                    chkCount++; 
                } 
            } 
        } 
    } 
    return chkCount; 
} 
/** 
 * 判断是不是有效的email地址 
 */ 
function IsValidateEmail(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return false; 
    } 
    //正则表达式 
    //var pattern = /^\w{1,}@[\.,\w]{1,}$/; 
    var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; 
    if (!pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的汉字 
 */ 
function checkIsHanzi(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return true; 
    } 
    //正则表达式 
    var pattern = /[^\u4E00-\u9FA5]/g; 
    if (pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的英文字母+(空格) 
 */ 
function checkIsLetter(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return true; 
    } 
    //正则表达式 
    var pattern = /[^a-zA-Z\s]/g; 
    if (pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
*判断是不是有效的英文字母+(空格或点) 
*/ 
function checkIsLetterOrSpaceDot(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return true; 
    } 
    //正则表达式 
    var pattern = /[^a-zA-Z\s\.]/g; 
    if (pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的英文字母和数字 
 */ 
function checkIsLetterNumber(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return true; 
    } 
    //正则表达式 
    var pattern = /[^a-zA-Z0-9\s]/g; 
    if (pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的数字(检查证件号码,密码用) 
 */ 
function checkIsNumber(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return true; 
    } 
    //正则表达式 
    var pattern = /[^0-9\s]/g; 
    if (pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的百分比数字 
 */ 
function checkIsPercent(str) { 
    //如果为空,则通过校验 
    if (str == "" || str.length == 0) { 
        return true; 
    } 
    //正则表达式 
    var pattern = /^[1-9][0-9]*%$/g; 
    if (!pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * check is validate time 
 */ 
function isValidateTime(str) { 
    if (parseInt(str) == 0) { 
        return true; 
    } 
    var regexp = /^(([0-9])|(0[0-9])|(1[0-9])|(2[0-3]))[0-5][0-9]$/ 
    if (str == "" || str.length == 0) { 
        return false; 
    } 
    if (!regexp.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的手机号码 
 * 格式正确返回true,否则false. 
 */ 
function IsValidateMobile(str) { 
    var pattern = /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/; 
    if (str == &#39;&#39; || str.length == 0) { 
        return false; 
    } 
    if (!pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的电话号码; 
 * 电话号码格式正确返回true,否则false. 
 */ 
function IsValidatePhone(str) { 
    var pattern = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/; 
    if (str == &#39;&#39; || str.length == 0) { 
        return false; 
    } 
    if (!pattern.test(str)) { 
        return false; 
    } 
    return true; 
} 
/** 
 * 判断是不是有效的邮政编码; 
 * 格式正确返回true,否则false. 
 */ 
function IsValidateZipcode(str) { 
    var pattern = /^[1-9]\d{5}$/; 
    if (str == &#39;&#39; || str.length == 0) { 
        return false; 
    } 
    if (!pattern.test(str)) { 
        return false; 
    } 
    return true; 
}
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles