search
HomeWeb Front-endJS TutorialSimple js form validation function_form effects

In website production, the form verification function is very commonly used.
Sometimes, it is more convenient to use some preformed js controls, but it is too large and difficult to maintain (my js level is not high)
So I simply wrote one myself. As for whether it is good or not, whether it is flexible or not, please give me some advice (the picture is shown first, it is ugly, please don’t mind):
Simple js form validation function_form effects

Code:

Copy code The code is as follows:

表单验证js代码

var fv =
{
    lang: "zh-cn",  //错误提示语言
    inValidedStr: "=",  //初始随意复制,使其长度不为0
    mail: function(elementID)   //验证邮件地址合法,elementID为input文本输入框的ID
    {
        if (elementID == null) { return true; }
        else
        {
            var reg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
            if (reg.test(document.getElementById(elementID).value))
            {
                fv.inValidedStr = fv.inValidedStr.replace(/mail/g, "");
                fv.inValidedStr = fv.inValidedStr.replace("=", "");
                validMsg(fv.lang, "mail", "mailInfo");
            }
            else
            {
                fv.inValidedStr = fv.inValidedStr + "mail";
                errorMsg(fv.lang, "mail", "mailInfo");
            }
        }
    },
    username: function(elementID)   //验证用户名合法 字母数字下划线,长度为6-20
    {
        if (elementID == null) { return true; }
        else
        {
            var reg = /^[a-zA-Z0-9_]{5,19}$/;
            if (reg.test(document.getElementById(elementID).value))
            {
                fv.inValidedStr = fv.inValidedStr.replace(/username/g, "");
                fv.inValidedStr = fv.inValidedStr.replace("=", "");
                validMsg(fv.lang, "username", "usernameInfo");
            }
            else
            {
                fv.inValidedStr = fv.inValidedStr + "username";
                errorMsg(fv.lang, "username", "usernameInfo");
            }
        }
    },

    //....可以加其他验证
    isValid: function() { return (fv.inValidedStr.length == 0); }
};

//验证成功时的信息 elementID 为信息提示的html单元的id
function validMsg(lang, valueType, elementID)
{
    var msgInfo = "";
    var isCn = lang == "zh-cn";

switch (valueType)
{
case "mail":
msgInfo = isCn ? " √ The address is valid" : " √ the mail address is valided";
break;
case "username":
msgInfo = isCn ? " √ Success" : " √ The account validated ";
break;
case "password":
msgInfo = isCn ? " √ Success" : √ Validated format!";
break;
//.....Correspondingly add other situations
default:
break;
}
document.getElementById(elementID).innerHTML = msgInfo;
document.getElementById(elementID).style.color = "green";
}

//Information when verification fails
function errorMsg(lang, valueType, elementID)
{
var msgInfo = "";
var isCn = lang == "zh-cn";

switch (valueType)
{
case "mail":
msgInfo = isCn ? " × Please enter the correct email address" : " × The e-mail format is error,plz input right format .eg. abc@def.com.";
               break; Underscores form ": " ;
                                                                                                             d(elementID ).style.color = "red";
}


Front-end code (aspx page):




Copy code


The code is as follows:


Front-end aspx page code
  < ;form id="form1" runat="server">
           

                                                                        ​ ;

                                                                             

Then, if you need other verification, just join. Related regular expressions




Copy code


The code is as follows:


匹配中文字符的正则表达式: [u4e00-u9fa5]
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
匹配双字节字符(包括汉字在内):[^x00-xff]
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
匹配空白行的正则表达式:ns*r
评注:可以用来删除空白行
匹配HTML标记的正则表达式:]*>.*?|
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
匹配首尾空白字符的正则表达式:^s*|s*$
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
评注:表单验证时很实用
匹配网址URL的正则表达式:[a-zA-z]+://[^s]*
评注:网上流传的版本功能很有限,上面这个基本可以满足需求
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
评注:表单验证时很实用
匹配国内电话号码:d{3}-d{8}|d{4}-d{7}
评注:匹配形式如 0511-4405222 或 021-87888822
匹配腾讯QQ号:[1-9][0-9]{4,}
评注:腾讯QQ号从10000开始
匹配中国邮政编码:[1-9]d{5}(?!d)
评注:中国邮政编码为6位数字
匹配身份证:d{15}|d{18}
评注:中国的身份证为15位或18位
匹配ip地址:d+.d+.d+.d+
评注:提取ip地址时有用

匹配特定数字:
^[1-9]d*$    //匹配正整数
^-[1-9]d*$   //匹配负整数
^-?[1-9]d*$   //匹配整数
^[1-9]d*|0$  //匹配非负整数(正整数 + 0)
^-[1-9]d*|0$   //匹配非正整数(负整数 + 0)
^[1-9]d*.d*|0.d*[1-9]d*$   //匹配正浮点数
^-([1-9]d*.d*|0.d*[1-9]d*)$  //匹配负浮点数
^-?([1-9]d*.d*|0.d*[1-9]d*|0?.0+|0)$  //匹配浮点数
^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$   //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]d*.d*|0.d*[1-9]d*))|0?.0+|0$  //匹配非正浮点数(负浮点数 + 0)
评注:处理大量数据时有用,具体应用时注意修正
匹配特定字符串:
^[A-Za-z]+$  //匹配由26个英文字母组成的字符串
^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串
^[a-z]+$  //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串
^w+$  //匹配由数字、26个英文字母或者下划线组成的字符串
在使用RegularExpressionValidator验证控件时的验证功能及其验证表达式介绍如下:
只能输入数字:“^[0-9]*$”
只能输入n位的数字:“^d{n}$”
只能输入至少n位数字:“^d{n,}$”
只能输入m-n位的数字:“^d{m,n}$”
只能输入零和非零开头的数字:“^(0|[1-9][0-9]*)$”
只能输入有两位小数的正实数:“^[0-9]+(.[0-9]{2})?$”
只能输入有1-3位小数的正实数:“^[0-9]+(.[0-9]{1,3})?$”
只能输入非零的正整数:“^+?[1-9][0-9]*$”
只能输入非零的负整数:“^-[1-9][0-9]*$”
只能输入长度为3的字符:“^.{3}$”
只能输入由26个英文字母组成的字符串:“^[A-Za-z]+$”
只能输入由26个大写英文字母组成的字符串:“^[A-Z]+$”
只能输入由26个小写英文字母组成的字符串:“^[a-z]+$”
只能输入由数字和26个英文字母组成的字符串:“^[A-Za-z0-9]+$”
只能输入由数字、26个英文字母或者下划线组成的字符串:“^w+$”
验证用户密码:“^[a-zA-Z]w{5,17}$”正确格式为:以字母开头,长度在6-18之间,

只能包含字符、数字和下划线。
验证是否含有^%&',;=?前台aspx页面代码



   
   


   

   

       
       

       

       
   

   




XXquot;等字符:“[^%&',;=?$x22] ”
只能输入汉字:“^[u4e00-u9fa5],{0,}$”
验证Email地址:“^w [- .]w )*@w ([-.]w )*.w ([-.]w )*$”
验证InternetURL:“^http://([w-] .) [w-] (/[w-./?%&=]*)?$”
验证电话号码:“^((d{3,4})|d{3,4}-)?d{7,8}$”

正确格式为:“XXXX-XXXXXXX”,“XXXX-XXXXXXXX”,“XXX-XXXXXXX”,

“XXX-XXXXXXXX”,“XXXXXXX”,“XXXXXXXX”。
验证身份证号(15位或18位数字):“^d{15}|d{}18$”
验证一年的12个月:“^(0?[1-9]|1[0-2])$”正确格式为:“01”-“09”和“1”“12”
验证一个月的31天:“^((0?[1-9])|((1|2)[0-9])|30|31)$”

正确格式为:“01”“09”和“1”“31”。

匹配中文字符的正则表达式: [u4e00-u9fa5]
匹配双字节字符(包括汉字在内):[^x00-xff]
匹配空行的正则表达式:n[s| ]*r
匹配HTML标记的正则表达式:/.*|/
匹配首尾空格的正则表达式:(^s*)|(s*$)
匹配Email地址的正则表达式:w ([- .]w )*@w ([-.]w )*.w ([-.]w )*
匹配网址URL的正则表达式:http://([w-] .) [w-] (/[w- ./?%&=]*)?
(1)应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
String.prototype.len=function(){return this.replace([^x00-xff]/g,"aa").length;}
(2)应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现
String.prototype.trim = function()
{
return this.replace(/(^s*)|(s*$)/g, "");
}
(3)应用:利用正则表达式分解和转换IP地址
function IP2V(ip) //IP地址转换成对应数值
{
re=/(d ).(d ).(d ).(d )/g //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3)) RegExp.$2*Math.pow(255,2)) RegExp.$3*255 RegExp.$4*1
}
else
{
throw new Error("Not a valid IP address!")
}
}
(4)应用:从URL地址中提取文件名的javascript程序
s="http://www.jb51.net/page1.htm";
s=s.replace(/(.*/){0,}([^.] ).*/ig,"$2") ; //Page1.htm
(5)应用:利用正则表达式限制网页表单里的文本框输入内容
用正则表达式限制只能输入中文:onkeyup="value="/blog/value.replace(/["^u4E00-u9FA5]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^u4E00-u9FA5]/g,''))"
用正则表达式限制只能输入全角字符: onkeyup="value="/blog/value.replace(/["^uFF00-uFFFF]/g,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^uFF00-uFFFF]/g,''))"
用正则表达式限制只能输入数字:onkeyup="value="/blog/value.replace(/["^d]/g,'') "onbeforepaste= "clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''))"
用正则表达式限制只能输入数字和英文:onkeyup="value="/blog/value.replace(/[W]/g,"'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,''

Statement
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
php怎么去除字符串中的所有大写字母php怎么去除字符串中的所有大写字母Sep 26, 2022 pm 07:59 PM

两种去除方法:1、利用preg_replace()执行正则表达式搜索所有大写字母并将其替换为空字符即可,语法“preg_replace('/[A-Z]/','',$str)”。2、利用preg_filter()执行正则表达式搜索所有大写字母并将其替换为空字符即可,语法“preg_filter('/[A-Z]/','',$str)”。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

使用Go语言编写高性能的正则表达式匹配使用Go语言编写高性能的正则表达式匹配Jun 15, 2023 pm 10:56 PM

随着数据量的不断增大,正则表达式匹配成为了程序中常用的操作之一。而在Go语言中,由于其天然的并行ism,以及与底层系统的交互性和高效性,使得Go语言的正则表达式匹配极具优势。那么如何使用Go语言编写高性能的正则表达式匹配呢?一、了解正则表达式在使用正则表达式前,我们首先需要了解正则表达式,了解其基本语法规则以及常用的匹配字符,使我们能够在编写正则表达式时更加

php怎么利用正则排除字符串中的字符php怎么利用正则排除字符串中的字符Dec 15, 2022 pm 03:30 PM

两种方法:1、用preg_replace(),可执行正则表达式的搜索和替换,只需将字符串中匹配的字符替换为空字符即可,语法“preg_replace(正则, "", $str)”。2、用preg_match_all(),可搜索字符串中所有和正则表达式匹配的结果,会将每次的匹配结果放在一个数组$array中,语法“preg_match_all(正则,$str,$array);”。

javascript怎么正则替换非汉字的字符javascript怎么正则替换非汉字的字符Oct 13, 2022 pm 05:37 PM

在javascript中,可以使用replace()函数配合正则表达式“/[u4e00-u9fa5|,]+/ig”来查找字符串中的所有非汉字字符,并将其替换为其他指定值,语法“字符串对象.replace(/[u4e00-u9fa5|,]+/ig,'指定替换值')”。

php怎么只获取中文字符php怎么只获取中文字符Apr 28, 2022 pm 08:15 PM

php中可用preg_match_all()配合正则表达式过滤字符串,只获取中文字符;语法“preg_match_all("/[\x{4e00}-\x{9fff}]+/u","$str",$arr);”,会将匹配字符存入“$arr”数组中。

Java语言正则表达式的使用方法Java语言正则表达式的使用方法Jun 10, 2023 am 08:13 AM

Java语言正则表达式的使用方法正则表达式是一种强大的文本处理工具,可以用来匹配和验证文本。在Java语言中,也可以使用正则表达式来实现字符串的匹配和处理。本文将介绍Java语言正则表达式的使用方法,涵盖正则表达式的基础知识,常用的正则表达式语法,以及在Java程序中使用正则表达式的方法。一、基础知识正则表达式是什么?正则表达式是一种文本模式,用来描述一组字

PHP开发:如何编写高效的正则表达式PHP开发:如何编写高效的正则表达式Jun 15, 2023 pm 09:04 PM

在PHP开发中,正则表达式是非常重要的工具,用于匹配、查找和替换文本中的特定字符串。然而,编写高效的正则表达式并不是一件易事,需要开发者具备一定的技巧和经验。下面是一些可以帮助您编写高效正则表达式的技巧:1.尽可能使用非贪婪匹配默认情况下,正则表达式是贪婪的,即它们将尽可能匹配更多的文本。在某些情况下,可能需要使用非贪婪匹配来避免这种情况。非贪婪匹配使用"

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version