Prefácio
Ao desenvolver projetos da Web, é inevitável encontrar vários dados de processamento de páginas da web, como a verificação do número de telefone, endereço de email, valor, número de identificação, comprimento de senha e complexidade inseridos pelo usuário no formulário e retornar ao plano de fundo
Formato de dados como o valor, o valor retornado é nulo e também há cálculo de um certo dia ou mês antes ou após a data especificada.
Abaixo estão alguns dos JS comumente usados em seu trabalho que você resumiu. Se você precisar, você pode consultar e aprender.
/** * Verify password complexity (must contain numeric letters) * @param str * @returns true:Satisfies the rule, false: Not satisfied */ function validateStr(str){ var reg1 = /^(([0-9]{1,})([az]{1,}))|(([az]{1,})([0-9]{1,}))$/; var reg2 = /^(([0-9] {1,}) ([az] {1,})) | (([az] {1,}) ([0-9] {1,})) $ /; // var reg3 = /^(par-za-z] {0, })[0-9a-Zaz] {0, }[~`!@#$%^&*. str = valuetrim (str); //if(reg3.test(str)) {// retorna true; //} if (reg1.test (str)) {return true; } if (reg2.test (str)) {return true; } retornar false; } / *** É julgado que o comprimento da string deve ser superior a 8 bits e menos de 20 bits, que geralmente é usado para senhas* @param str string* @return se satisfazer retorno true* / função validatElngth (str) {if (str == null || str == '') {return false; } str = valuetrim (str); if (parsefloat (str.Length) <8) {return true */ function validatElngth (str) {if (str == null || str == '') {return false; } str = valuetrim (str); if (parsefloat (str.Length) <8) {return true */ function validatElngth (str) {if (str == null || str == '') {return false; } str = valuetrim (str); if (parsefloat (str.length) <8) {return false; } if (parsefloat (str.length)> 20) {return false; } retornar true; } / ** * Tempo de verificação * @param datavalue O formato é: yyyy-mm-dd * @return the Match retorna true se a correspondência não corresponder retorna false * / function valid (dateValue) {var resultado = DateValue.Match (/((^((1 [8-9]/d {2}) | ([2-9]/d {3})) (-) (10 | 12 | 0? [13578]) ( -) (3 [01] | [12] [0-9] | 0? [1-9]) $) | (^((1 [8-9]/d {2}) | ([2-9]/d {3})) (-) (11 | 0? [469]) (-) (30 | [12] [0-9] | 0? [1-9]) $) | (^((1 [8-9]/d {2}) | ([2-9]/d {3}) (-) (0? [2468] [048] 00) (-) (0? 2) (-) (29) $) | (^([2468] [048] 00) (-) (0? 2) (-) (29) $) | (^([2468] [048] 00) (-) (0? ([3579] [26] 00) (-) (0? 2) (-) (29) $) | (^([1] [89] [0] [48]) (-) (0? 2) (-) (29) $) | ( ^([2-9] [0-9] [0] [48]) (-) (0? 2) (-) (29) $) | (^([1] [89] [2468] [048]) (-) (0? 2) ( -) (29) $) | (^([2-9] [0-9] [2468] [048]) (-) (0? 2) (-) (29) $) | (^([1] [89] [13579] [26]) (-) (0? 2) (-) (29) $) | (^([2-9] [0-9] [13579] [26]) (-) (0? 2) (-) (29) $))/); if (resultado == null) {return false; } retornar true; } / *** Verifique se o número de telefone* @param PhoneValue o número de telefone a ser verificado* @return the Match retorna true se a incompatibilidade retornar falsa* / function ValidatePhone (PhoneValue) {PhoneValue = Valuetrim (PhoneValue); var reg = /^[1] [0-9] {10} $ /; Return Reg.test (PhoneValue); }/***Verifique se o email*@param emailvalue o email a ser verificado*@return the Match retorna true se a incompatibilidade retornar falsa*/função validemail (emailvalue) {var reg = /^/w+(/w-li-/w+)*/w+(/.-/17 retornar reg.test (emailvalue); } /*** Determine se é um número* @param NumberValue os dados a serem verificados* @return the Match retorna true se a correspondência não corresponder retorna false* /function isNumber (numberValue) {// Defina a peça de expressão regular var var Reg1 = /^[0-9] {0,} $ /; var reg2 = /^[1-9] {1} [0-9] {0,} $ /; // alerta (numberValue); if (numberValue == null || numberValue.Length == 0) {return false; } numberValue = valuetrim (numberValue); // julga quando o número é apenas 1 bit se (numberValue.Length <2) {return reg1.test (numberValue); } retornar reg2.test (numberValue) ;; } / **** valor* @param valor* @returns* / função ismoney (value) {if (value == '') {return false; } value = valuetrim (valor); value = value.replace (/(^/s*) | (/s*$)/g, ""); var reg = /^.0-9 ]*/.? if (isNumber (value)) {return true; } if (value.length> 3) {if (value.substr (0, 1) == "0") {if (value.substr (3, value.length) .length> 2) {return false; }}} retornar reg.test (valor); } / **** Determine se é um número entre 0 e 100* @param value* @RETURNS* / função isZeroone (value) {if (value == '') {return false; } value = valuetrim (valor); if (ismyfloat (value)) {if (parsefloat (value) <100 && parsefloat (value)> 0) {return true; }} retornar false; } / *** Verifique se é um número de ponto flutuante* @param floatValue os dados a serem verificados* @return the Match retorna true se a incompatibilidade retornar falsa* / function ismyfloat (floatValue) {if (floatValue == ') {return false; } floatValue = valuetrim (floatValue); var reg = /^(/d+)(/./d+)$/; if (isNumber (floatValue)) {return true; } if (floatValue.length> 3) {if (floatValue.substr (0, 1) == "0") {if (floatValue.substr (0, 2)! = "0.") {return false; }}} retornar reg.test (floatValue); }/*** Determine se é um caractere chinês* @param charvalue dados a serem verificados* @returns corresponde retorna true se uma correspondência não corresponder retorna false*/função ischaracter (Charvalue) {var =/^[/u4e00-/u9fa5] {0,} $/; Reg.test de retorno (Charvalue); }/*** Verifique o número do telefone fixo* @param telvalue O número do telefone fixo a ser verificado* @returna a partida retorna true se a incompatibilidade retornar falsa*/função validateTel (telValue) {var reg =/^(/(/d {3,4}/)/d {3,4}-)? telvalue = valuetrim (telvalue); if (! reg.test (telValue)) {return false; } retornar true; } var Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]; // fator de ponderação var validecode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; // The ID card verification bit value.10 represents X /** * Verify ID card* @param idCard The ID card number that needs to be verified* @returns The match returns true If the match does not match returns false */ function IdCardValidate(idCardValue) { // Remove the string head and tail spaces idCardValue = valueTrim(idCardValue.replace(/ /g, "")); if (iDCardValue.Length == 15) {// Verifique o cartão de identificação de 15 bits retorna isValityBrithby15idcard (IDCardValue); } else if (iDCardValue.Length == 18) {// Obtenha a matriz de cartões de identificação var a_idcard = idcardValue.split (""); // Execute a verificação básica do cartão de identificação de 18 bits e verificação de 18 bits se (isValityBrithBy18idCard (IDCardValue) && isTRUEVALIDACODEBY18IDCARD (A_IDCARD)) {return true; } else {return false; }} else {return false; }} / *** Determine se o último bit de verificação está correto quando o número do cartão de identificação é de 18 bits* @param a_idcard Número da matriz* @return* / function isTruevalidateCodeBy18idCard (a_idcard) {var sum = 0; // Declare a variável da soma ponderada if (a_idcard [17] .tolowerCase () == 'x') {a_idcard [17] = 10; // Substitua o código de verificação pelo último bit x com 10 para operações subsequentes} para (var i = 0; i <17; i ++) {sum+= wi [i] 11; // a posição do código de verificação obtido se (a_idcard [17] == Validecode [valcodePosition]) {return true; } else {return false; }} / *** Verifique se o aniversário do número do cartão de identificação de 18 dígitos é um aniversário válido* @param idcard 18 dígitos Id String* @return* / função isValityBrithby18idcard (idcard18) {var ano = idcard18.substring (6,10); var mês = idcard18.substring (10,12); var dia = idcard18.substring (12,14); var temp_date = nova data (ano, parsefloat (mês) -1, parsefloat (dia)); // Use Getlyear () aqui para obter o ano para evitar o problema do bug do milênio se (temp_date.getlyear ()! = Parsefloat (ano) || temp_date.getmonth ()! = Parsefloat (mês) -1 || temp_date.getdate ()! } else {return true; }} / *** Verifique se o aniversário do número de cartões de identificação de 15 dígitos é um aniversário válido* @param idcard15 Id de livro de 15 dígitos String* @return* / função isValithBrithby15idcard (idcard15) {var ano = idcard15.substring (6,8); var mês = idcard15.Substring (8,10); var dia = idcard15.Substring (10,12); var temp_date = nova data (ano, parsefloat (mês) -1, parsefloat (dia)); // Para a sua idade no seu cartão de identificação antigo, você não precisa considerar o problema do Millennium Bug e usar o método getyear () se (temp_date.getyear ()! = Parsefloat (ano) || temp_date.getmonth ()! = Parsefloat (mês) -1 | } else {return true; }} // Remova os espaços da cabeça e da cauda da função valuetrim (str) {return str.replace (/(^/s*) | (/s*$)/g, ""); } /** * Check the 18-digit ID number (15-digit number can only detect whether the birthday is correct, and solve it yourself) * @param idCardValue 18-digit ID number* @returns Match returns true If the mismatch returns false */ function idCardVildate(cid){ var arrExp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // fator de ponderação var ArrValid = [1, 0, "x", 9, 8, 7, 6, 5, 4, 4, 3, 2]; // Código de verificação var reg = /^[1-9]/d {5} [1-9]/d {3} ((0/d) | (1 [0-2])) (([0 | 1 | 2]/d) | 3 [0-1])/d {3} ([0-9] | x) $/; if (reg.test (cid)) {var sum = 0, idx; for (var i = 0; i <cid.length - 1; i ++) {// soma da soma dos primeiros 17 dígitos e pesos+= parseint (cid.substr (i, 1), 10) * arrexp [i]; } // Calcule o módulo (algoritmo fixo) idx = soma % 11; // Verifique se o 18º é igual ao código de verificação Retorno ARRVALID [IDX] == CID.SUBSTR (17, 1) .TOUPPERCASE (); } else {return false; }} / ** * Obtenha um dia antes ou depois da data especificada * * @Param DayCount * Número positivo é o tempo futuro, o número negativo é o horário anterior, como: 1 é expresso como amanhã, -1 é ontem * * / função getDatest (datas, dia) {var dateTeTime = DayCount * 24 * 60 60 * 60 * 1000; var dd = new Date (); if (datas == "") {dd = new Date (); } else {dd = nova data (datas); } var datenumber = dd.gettime () + dateTime; var newDate = new Date (DatenBumber); var y = newDate.getlyear (); var m = newDate.getMonth () + 1; // Obtenha a data do mês atual var d = newDate.getDate (); if (m <10) {m = "0" + m; } if (d <10) {d = "0" + d; } retornar y + "-" + m + "-" + d; } / ** * Obtenha o mês anterior ou depois do mês especificado * * @param DayCount * Número positivo é o próximo mês, o número negativo é o mês anterior, como: 1 é o próximo mês, -1 é o mês anterior * * / function getmontstr (datas, mensagens) {var dd = new Date (); if (datas == "") {dd = new Date (); } else {dd = nova data (datas); } var y = dd.getlyear (); var m = dd.getmonth () + 1; // obtenha a data do mês atual m = m + mês; if (m == 0) {m = "12"; y = y - 1; } else if (m <10) {m = "0" + m; } else if (m> 12) {m = m - 12; m = "0" + m; y = y + 1; } retornar y + "-" + m; } / *** retornar "" para o valor Val é indefinido, caso contrário, retorne o valor original* / função DealNull (val) {if (typeof (val) == "indefinido") {return ""; } else {return val; }}Resumir
O exposto acima são as informações de verificação e processamento de dados mais práticas compiladas para todos, o que é muito útil para o trabalho diário de todos. Recomenda -se que você o coleta para facilitar a revisão no futuro. Obrigado pelo seu apoio ao wulin.com.