Home Web Front-end JS Tutorial JS form validation code (commonly used)_javascript skills

JS form validation code (commonly used)_javascript skills

May 16, 2016 pm 03:06 PM

最近没有项目做,有点空余时间,小编把日常比较常用的js表单验证代码整理分享到脚本之家平台,供大家学习,需要的朋友参考下吧!

注册验证:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

<script language="JavaScript" src="js/jquery-1.9.1.min.js" type="text/javascript"></script>

//验证表单

function vailForm(){

var form = jQuery("#editForm");

if(!vailNickName())return;

if(!vailPhone())return;

if(!vailPwd())return;

if(!vailConfirmPwd())return;

if(!vailEmail())return;

if(!vailCode())return;

if(!vailAgree())return;

form.submit();

}

//验证昵称

function vailNickName(){

var nickName = jQuery("#nickName").val();

var flag = false;

var message = "";

var patrn=/^\d+$/;

var length = getNickNameLength();

if(nickName == ''){

message = "昵称不能为空!";

}else if(length<4||length>16){

message = "昵称为4-16个字符!";

} else if(checkNickNameIsExist()){

message = "该昵称已经存在,请重新输入!";

}else{

flag = true;

}

if(!flag){

jQuery("#nickNameDiv").removeClass().addClass("ui-form-item has-error");

jQuery("#nickNameP").html("");

jQuery("#nickNameP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);

//jQuery("#nickName").focus();

}else{

jQuery("#nickNameDiv").removeClass().addClass("ui-form-item has-success");

jQuery("#nickNameP").html("");

jQuery("#nickNameP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该昵称可用");

}

return flag;

}

//计算昵称长度

function getNickNameLength(){

var nickName = jQuery("#nickName").val();

var len = 0;

for (var i = 0; i < nickName.length; i++) {

var a = nickName.charAt(i);

      //函数格式:stringObj.match(rgExp) stringObj为字符串必选 rgExp为正则表达式必选项

      //返回值:如果能匹配则返回结果数组,如果不能匹配返回null

if (a.match(/[^\x00-\xff]/ig) != null){

len += 2;

}else{

len += 1;

}

}

return len;

}

//验证昵称是否存在

function checkNickNameIsExist(){

var nickName = jQuery("#nickName").val();

var flag = false;

jQuery.ajax(

{ url: "checkNickName&#63;t=" + (new Date()).getTime(),

data:{nickName:nickName},

dataType:"json",

type:"GET",

async:false,

success:function(data) {

var status = data.status;

if(status == "1"){

flag = true;

}

}

});

return flag;

}

//验证手机号

function vailPhone(){

var phone = jQuery("#phone").val();

var flag = false;

var message = "";

//var myreg = /^(((13[0-9]{1})|159|153)+\d{8})$/;

var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-3]{1})|(18[5-9]{1}))+\d{8})$/;

if(phone == ''){

message = "手机号码不能为空!";

}else if(phone.length !=11){

message = "请输入有效的手机号码!";

}else if(!myreg.test(phone)){

message = "请输入有效的手机号码!";

}else if(checkPhoneIsExist()){

message = "该手机号码已经被绑定!";

}else{

flag = true;

}

if(!flag){

jQuery("#phoneDiv").removeClass().addClass("ui-form-item has-error");

jQuery("#phoneP").html("");

jQuery("#phoneP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);

//jQuery("#phone").focus();

}else{

jQuery("#phoneDiv").removeClass().addClass("ui-form-item has-success");

jQuery("#phoneP").html("");

jQuery("#phoneP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该手机号码可用");

}

return flag;

}

//验证手机号是否存在

function checkPhoneIsExist(){

var phone = jQuery("#phone").val();

var flag = true;

jQuery.ajax(

{ url: "checkPhone&#63;t=" + (new Date()).getTime(),

data:{phone:phone},

dataType:"json",

type:"GET",

async:false,

success:function(data) {

var status = data.status;

if(status == "0"){

flag = false;

}

}

});

return flag;

}

//验证密码

function vailPwd(){

var password = jQuery("#password").val();

var flag = false;

var message = "";

var patrn=/^\d+$/;

if(password ==''){

message = "密码不能为空!";

}else if(password.length<6 || password.length>16){

message = "密码6-16位!";

}else if(patrn.test(password)){

message = "密码不能全是数字!";

}else{

flag = true;

}

if(!flag){

jQuery("#passwordDiv").removeClass().addClass("ui-form-item has-error");

jQuery("#passwordP").html("");

jQuery("#passwordP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);

//jQuery("#password").focus();

}else{

jQuery("#passwordDiv").removeClass().addClass("ui-form-item has-success");

jQuery("#passwordP").html("");

jQuery("#passwordP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该密码可用");

}

return flag;

}

//验证确认密码

function vailConfirmPwd(){

var confirmPassword = jQuery("#confirm_password").val();

var patrn=/^\d+$/;

var password = jQuery("#password").val();

var flag = false;

var message = "";

if(confirmPassword == ''){

message = "请输入确认密码!";

}else if(confirmPassword != password){

message = "二次密码输入不一致,请重新输入!";

}else if(patrn.test(password)){

message = "密码不能全是数字!";

}else {

flag = true;

}

if(!flag){

jQuery("#confirmPasswordDiv").removeClass().addClass("ui-form-item has-error");

jQuery("#confirmPasswordP").html("");

jQuery("#confirmPasswordP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);

//jQuery("#confirm_password").focus();

}else{

jQuery("#confirmPasswordDiv").removeClass().addClass("ui-form-item has-success");

jQuery("#confirmPasswordP").html("");

jQuery("#confirmPasswordP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>密码正确");

}

return flag;

}

//验证邮箱

function vailEmail(){

var email = jQuery("#email").val();

var flag = false;

var message = "";

var myreg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

if(email ==''){

message = "邮箱不能为空!";

}else if(!myreg.test(email)){

message = "请输入有效的邮箱地址!";

}else if(checkEmailIsExist()){

message = "该邮箱地址已经被注册!";

}else{

flag = true;

}

if(!flag){

jQuery("#emailDiv").removeClass().addClass("ui-form-item has-error");

jQuery("#emailP").html("");

jQuery("#emailP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);

//jQuery("#email").focus();

}else{

jQuery("#emailDiv").removeClass().addClass("ui-form-item has-success");

jQuery("#emailP").html("");

jQuery("#emailP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>该邮箱可用");

}

return flag;

}

//验证邮箱是否存在

function checkEmailIsExist(){

var email = jQuery("#email").val();

var flag = false;

jQuery.ajax(

{ url: "checkEmail&#63;t=" + (new Date()).getTime(),

data:{email:email},

dataType:"json",

type:"GET",

async:false,

success:function(data) {

var status = data.status;

if(status == "1"){

flag = true;

}

}

});

return flag;

}

//验证验证码

function vailCode(){

var randCode = jQuery("#randCode").val();

var flag = false;

var message = "";

if(randCode == ''){

message = "请输入验证码!";

}else if(!checkCode()){

message = "验证码不正确!";

}else{

flag = true;

}

if(!flag){

jQuery("#randCodeDiv").removeClass().addClass("ui-form-item has-error");

jQuery("#randCodeP").html("");

jQuery("#randCodeP").html("<i class=\"icon-error ui-margin-right10\"> <\/i>"+message);

//jQuery("#randCode").focus();

}else{

jQuery("#randCodeDiv").removeClass().addClass("ui-form-item has-success");

jQuery("#randCodeP").html("");

jQuery("#randCodeP").html("<i class=\"icon-success ui-margin-right10\"> <\/i>");

}

return flag;

}

//检查随机验证码是否正确

function checkCode(){

var randCode = jQuery("#randCode").val();

var flag = false;

jQuery.ajax(

{ url: "checkRandCode&#63;t=" + (new Date()).getTime(),

data:{randCode:randCode},

dataType:"json",

type:"GET",

async:false,

success:function(data) {

var status = data.status;

if(status == "1"){

flag = true;

}

}

});

return flag;

}

//判断是否选中

function vailAgree(){

if(jQuery("#agree").is(":checked")){

return true;

}else{

alert("请确认是否阅读并同意XX协议");

}

return false;

}

function delHtmlTag(str){ var str=str.replace(/<\/&#63;[^>]*>/gim,"");//去掉所有的html标记 var result=str.replace(/(^\s+)|(\s+$)/g,"");//去掉前后空格 return result.replace(/\s/g,"");//去除文章中间空格}<!DOCTYPE html><html><body><h1>我的第一段 JavaScript</h1><p>请输入数字。如果输入值不是数字,浏览器会弹出提示框。</p><input id="demo" type="text"><script>function myFunction(){var x=document.getElementById("demo").value;if(x==""){ alert("输入不能为空"); return;}if(isNaN(x)){ alert("请输入数字"); return;}if(x.length!=6){ alert("请输入6位数字"); return;}}</script><button type="button" onclick="myFunction()">点击这里</button></body></html>

//验证密码为数字字母下划线

function CheckPwd(pwd) {

var validStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_~/!@#$%^&*();-+.=,";

for (i = 0; i < pwd.length; i++) {

if (validStr.indexOf(pwd.charAt(i)) == -1) {

return false;

}

}

return true;

}

//验证邮箱格式

function checkemail(email) {

var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

if (!filter.test(email)) {

return false;

}

return true;

}

function isEmail(val) {

return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\&#63;\^_\`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\&#63;\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))&#63;(\x20|\x09)+)&#63;(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))&#63;(\x20|\x09)+)&#63;(\x22)))@((([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])))\.&#63;$/.test(val);

}

///手机号码验证

function checktelephone(cellPhone) {

var RegCellPhone = /^([0-9]{11})&#63;$/;

falg = cellPhone.search(RegCellPhone);

if (falg == -1) {

return false;

} else {

return true;

}

}

//获取URL参数值

function getParameter(param) {

var query = window.location.search;

var iLen = param.length;

var iStart = query.indexOf(param);

if (iStart == -1)

return "";

iStart += iLen + 1;

var iEnd = query.indexOf("&", iStart);

if (iEnd == -1)

return query.substring(iStart);

return query.substring(iStart, iEnd);

}

Copy after login

以上代码是小编给大家介绍的js表单验证,代码简单易懂,非常实用,希望对大家有所帮助,同时也非常感谢大家对脚本之家网站的支持!

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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

jQuery Matrix Effects jQuery Matrix Effects Mar 10, 2025 am 12:52 AM

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of ​​the picture and uses jQuery to calculate the average color of each area. Then, use

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How to Build a Simple jQuery Slider How to Build a Simple jQuery Slider Mar 11, 2025 am 12:19 AM

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Enhancing Structural Markup with JavaScript Enhancing Structural Markup with JavaScript Mar 10, 2025 am 12:18 AM

Key Points Enhanced structured tagging with JavaScript can significantly improve the accessibility and maintainability of web page content while reducing file size. JavaScript can be effectively used to dynamically add functionality to HTML elements, such as using the cite attribute to automatically insert reference links into block references. Integrating JavaScript with structured tags allows you to create dynamic user interfaces, such as tab panels that do not require page refresh. It is crucial to ensure that JavaScript enhancements do not hinder the basic functionality of web pages; even if JavaScript is disabled, the page should remain functional. Advanced JavaScript technology can be used (

How to Upload and Download CSV Files With Angular How to Upload and Download CSV Files With Angular Mar 10, 2025 am 01:01 AM

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular

See all articles