Os exemplos deste artigo compartilham com você a estrutura de verificação do JS, que é muito prática para sua referência. O conteúdo específico é o seguinte
1. Métodos e princípios -chave:
if (! Eval (scriptcode)) no método de verificação da função (thisInput) {return false; }2. Exemplo de chamada:
Copie o código do código da seguinte forma: <input type = "text" name = "progress_payment_two" id = "progress_payment_two" inputName = "Progress Payment 2 ratio (%)" validate = "isnumeric; notnull" maxLength = "350" "" " />
3. O método isnumérico e o método NotNull serão chamados automaticamente durante a verificação e as informações do resultado da verificação serão retornadas.
4. O código -fonte da estrutura de verificação é o seguinte
var configValidateInfotype = "writealert"; // suporta WritEalert e WritePage, "WritePage; WritEalert" var rmtempStatusisalert = false; var rmtempstatusisfocus = false; var BeginValidate = true; var set_all_venus_inputs_default = true; String.prototype.trim = function () {return this.replace (/(^/s*) | (/s*$)/g, ""); } função checkallforms () {var checkResult = true; rmtempStatusIsalert = false; rmtempstatusisfocus = false; setAllvenUSInputsDefault (); for (var i = 0; i <document.forms.length; i ++) {for (var j = 0; j <document.forms [i] .Elements.Length; j ++) {var thisInput = document.forms [i] .Elements [j]; if (thisInput.type! = "Hidden" && thisInput.Type! = "Button" &&! (thisInput.id.indexof ("tf _")> = 0 && thisInput.id.indexof ("_ tf")> 0) && thisInput.clientWidth! = 0 && thisInput.style && thisInput.style.display! = 'None') { /* if (validateSTest! if (thisInput.MaxLength! = null && thisInput.maxLength> 0) {if (thisInput.TagName == 'texttarea' && srcstr! = '') {srcstr = replyEnter (srcstr); if (thisInput.MaxLength! = null && thisInput.maxLength> 0) {if (getStrLength (srcstr)> thisInput.maxLength) {writeValidateInfo (}} if (thisInput.id && thisInput.id.indexof ("Supplier_id_ref _")! CheckResult = FALSO; (var i = 0; i <validateTemp.length; i ++) {if (validateTemp [i] .Length == 0) {continua; "ThisInput)" if (validateTemp [i] .IndexOf ("(") <0 || validateTemp [i] .IndexOf (")") <0) {scriptcode = "javascript:" + validateMp [i] + ", thisinput)"}}} {! função "+validateTEMP [i]+" Existe uma exceção, verifique! "+"/n "+e.message); retorna false;}}} retorna true;} função setallvenUsinputsDefault () {var frmsLen = document.forms.length; para (var i = 0; i <frmsLen; j = 0; j <inslen; j ++) {var frm = document.forms [i] .Elements [j] if (frm.Type! = "Hidden" && frm.Type! = "Button" &&! (frm.id.indexof ("tf _")> = 0 && FRM.ID.INDEXF ("_TF") setvenuSInputDault (FRM); _frm.style.backgroundcolor = ""; se (str.indexof ('/n')! =-1 && str.indexof ('/r')! Str.Place ('/' ',' // u0027 '); str.Redplace ('(', '// u0028'); str = str.Replace ('(', '// u005c'); str = str.replace ('//', '// u0027'); str str.; str.replace ('/"', '// u0022'); str = str.replace (';', '// u0038'); // str = jtrim (str); retorna str;} função iSContans (_ValidATestSest, _Validator) {para (var i = 0; i <_ _ValidTest.Llingn; _Validador) Retorne true; thisObj); // Frm.Click (); _frm.style.bordercolor = "rgb (255,50,0)"; WriteValidateInfoalert (info, thisobj) {if (! rmtempstatusisalert) {alert (info); if (thisObj.Nextsibling! = null && thisObj.nextsibling.nextsibling! = null && thisobj.nextsibling.tagname! "Span" && thisobj.nextsibling.nextsibling.className == "font_remain_prompt") {validateInfoobj = thisobj.nextsibling.nextSibling; class = font_remain_prompt> </span> "); validateInfoObj = thisObj.nextsibling.nextsibling;} if (validateInfoObj.innerhtml.length> 0 || info.length> 0) {ValidEnFoobj.innerHtml =; if (thisObj.nextsibling! = null && thisobj.nextsbling.className == "refbuttonClass") {thisobj = getValidatePosition (thisobj.nextSibling); getValidesPoition (ThisObj.NextSibling); ) {inputName = ""; /********************************************* thisInput.Value = ThisInput.Value.Trim (); FALSO; }} função ismobile (s, thisInput) {// emita o número do celular: deve começar com um número, exceto o número, pode conter "-" // Remover o espaço tente {thisInput.value = thishut.value.trim (); obj [0] = 13 "; s.substring (0,2) == obj [int]) {mob = mob+1; ]) {1,12})+$/; } captura (e) {} s = s.trim (); ISTEL (S, ThisInput) {// É um número de telefone normal e um número de fax: pode começar com "+", exceto os números, pode conter "-" // Remover o espaço, tente {thisInput.Value = ThisInput.value.trim (); patrn =/^[+] {0,1} (/d) {1,3} []? ([-]? (((/d) | []) {1,12})+$/; if (! Patrn.exec (s)) {writeValidateInfo ('por favor, um número de telefone legal! // é um número de telefone normal e um número de fax: pode começar com "+", exceto o número, pode conter "-" // Remover o espaço tente {thisInput.value = ThisInput.value.trim (); patn =/^(/d) {3,4} [-] (/d) {7,8} $/; Número: ele pode começar com "+", exceto o número, pode conter "-" // Remover o espaço, tente {thisInput.value = ThisInput.value.trim (); (! patn.exec (s)) {writeValidateInfo ('Por favor, insira um número de fax legal, por exemplo: 010-8888888!', ThisInput); s = s.trim (); } captura (e) {} s = s.trim (); ThisInput.Value = ThisInput -1) {writeValateInfo (digite o número! } var digits = 0123456789 "; if (thisInput.Value <= 0) {writeValidEInfo ("o valor de entrada deve ser maior que zero!", esse flowInput); if (s.Length == 0) {retorna true; /^(([0-9a-za-z]+) | ([0-9a-za-z]+[_. .]))+([a-za-z] {2} | net | net | com | com | gov | gov | mil | mil | org | org | edu | edu | int | int) $/; if (regum.exec (s)) {retorna true; thisInput); /*************************************** ******************************************* Verifique se o NotNull *************************************** 0) {writeValateInfo ('Por favor, digite, este item não pode ser vazio!', Esse flowInput); true; isNormalStronWeb (S, ThisInput) {// é um caractere normal (tag não-html) se (s.substring (0,1) == "<" || s.substring (0,1) == "//" | If (! 0) {if (s.IndexOf ("/" ")> -1) {writeValidateInfo (" aspas duplas não podem ser inseridas no foco !! ", thisInput); retorna false;} if (s.Indexof ("/'")> -1) {writeValidEInfo (" ÚNICO ÚNICO NÃO PODE SER ENCONTRADO NO FOCO ",, this" this "this); -1) {writeValidateInfo ("" "Não pode ser inserido no foco", esse input); retornar false;}} retornar true;} // Função de função básica Função JTRIM (str) {// function de despacho var i = 0; var len = str.Length; if (str == ") retorno (stre); var j = len; && i <len) {if (str.charat (i) == "") {i = i+1; (" O que você precisa saber para começar o dia bem -informado /*************************************** aperfeiçoado) ********************************************************* validateForm (current_form) {for (var i = 0; i <current_form.length; i ++) {if (current_form [i] .type == "text" || current_form [i] .Type == "Radio") {if (current_form [i] .Value.substring (0,... "/>" O comprimento é muito longo no foco/n verifique se o comprimento da entrada está dentro de " +current_form [i] .MaxLength +"); foco/"・/" // " -/" // " -/" // " -/" // " -/" -/"//" -/"); "scriptDefine") {retorna true; o espaço Experimente {ThisInput.Value = ThisInput.Value.trim (); } Catch (e) {}} Função CheckNumberImpl (S, MAXLENGE, escala) {// Verifique a milhagem em execução, decimal e parte inteira no máximo 10-2 se (s == "") {retorna true; if (! isfloatNumber (s)) {return false; (MAXLEGRO - Escala) + bits! "); ThisInput.value Digits.indexof (c) Issarch (s, thisInput) {// não pode inserir caracteres ilegais se (s.length == 0) retornar true; patn =/^[^`~!@#$%^&*()+= | ///] [/]/{/} :; '/,. <>/?] {1} [^` ~!@$%^& ()+= | ///] [/]/{/}: /−/{/|/.//,<>"'_}/ ]/; if (! patn.exec (s) ||! patn2.exec (s)) {writeValidateInfo ('A entrada contém caracteres ilegais, por favor, volte-se!', ThisInput); retornar false;} Return True;} // ============================================================= ============================================================/** * Verifique o número (número inteiro positivo e o número de decimais) (! Reg.test (Valor) {WriteValidEInfo ("Digite um número inteiro positivo ou decimal! Valor = Valor.Trim (); */função validatenumericandlength (valor, thisInput) {// Remova o espaço, tente {thisInput.value = ThisInput.value.trim (); {writeValidateInfo ("Digite um número inteiro positivo ou decimal (o dígito inteiro pode ter apenas 10 dígitos)!", ThisInput); } catch (e) {} value = value.trim (); this iStInput); /^(-)? ThisInput) {// Remova o espaço, tente {thisInput.Value = ThisInput.value.trim (); ("Digite um número (até 3 dígitos inteiros, máximo para 2 locais decimais)! ut.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg = /^/w+([-+. ]/w+)*@/w+([-.bory/w+)*/./w+ tiver if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite o endereço de email correto!", EsteInput); retornar falso; } retornar true;} /*** Verifique o cartão de identificação (cartão de identificação de 15 ou 18 bits). */function checkIdCard (valor, thisInput) {// remova o espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg =/^/d {15} (/d {2} [a-za-z0-9])? $/; if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite o número de identificação correto!", ThisInput); retornar falso; } retornar true;} /*** Verifique o código postal. */função checkPostCode (valor, thisInput) {// remova o espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg =/^[0-9]/d {5} $/; if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite o código postal correto!", ThisInput); retornar falso; } retornar true;} /*** Verifique se é um caractere chinês. */função verificação de verificação (valor, thisInput) {// remova o espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg =/^[/u0391-/uffe5]+$/; if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite caracteres chineses!", ThisInput); retornar falso; } retornar true;} /*** Verifique se é um caráter ilegal. */função checkInValidString (valor, thisInput) {var reg = /^[^`~!@#$%^&*(+=| pressado if (! reg.exec (value)) {writeValidateInfo ("O caractere inserido contém caracteres especiais, entre em volta!", ThisInput); retornar falso; } retornar true; } função checkMoney (s, inputName) {// remova o espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} s = s.trim (); if (s.length == 0) {return true; } if (s == "") {writeValidateInfo ("A quantidade não pode estar vazia!", InputName); retornar falso; } if (isfloatNumber (s, inputName) == false) {writeValidateInfo ("valor ilegal de valor!", inputName); retornar falso; } var maxLength = 10; var scale = 2; Retornar CheckNumberImpl (S, MaxLength, Scale, InputName);}/** * Verifique se a pontuação é 0-100 */função isadultage (str, thisInput) {// é um número inteiro // remover o espaço tente {thisInput.value = thisInput.value.Trim (); } catch (e) {} str = str.trim (); if (str.Length == 0) {return true; } if (parseint (str) <0 || parseint (str)> 100) {writeValidateInfo ('Por favor, insira uma pontuação legal (entre 0-100)!', ThisInput); retornar falso; } retornar true;} /** * Configurações de intensidade de nível 6 (número, maiúscula, letras minúsculas, caracteres especiais, comprimento> = 6, comprimento> = 10) * Se a senha estiver vazia, retorne 0 * /função pwdStrength (pwd) {var sum = [0, 0]; for (var i = 0; i <pwd.length; i ++) {var c = pwd.charcodeat (i); if (c> = 48 && c <= 57) // soma do número [0] = 1; caso contrário, if (c> = 65 && c <= 90) // soma uppercase [1] = 1; else if (c> = 97 && c <= 122) // soma minúscula [1] = 1; else // soma especial de caractere [2] = 1; } var nível = soma [0] + soma [1] + soma [2]; if (pwd.length> = 8) nível ++; Nível de retorno;} função isbiggerzero (valor, thisInput) {// já um número, então deve ser maior que 0 se (thisInput.value <= 0) {writeValidateInfo ('Por favor, digite um número maior que zero!', thisInput); retornar falso; } retornar true;} função isNonnegative (valor, thisInput) {if (thisInput.Value <0) {writeValidateInfo ('por favor digite um número não negativo!', ThisInput); retornar falso; } retornar true;} /** * Verifique o número (20,6) * /função isnum20p6 (valor, thisInput) {// remova espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg = /^(-)? if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite um número (o máximo de 14 dígitos inteiros e o máximo de 6 dígitos decimais)!", ThisInput); retornar falso; } retorna isbiggerZero (valor, thisInput);} /** * Verifique o número (18,6) * /função isnum18p6 (value, thisInput) {// remova o espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg = /^(-)? if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite um número (o máximo de 12 dígitos inteiros e o máximo de 6 dígitos decimais)!", ThisInput); retornar falso; } retorna isbiggerZero (value, thisInput);} função isNonnegative20p6 (value, thisInput) {// remova o espaço tente {thisInput.value = thisInput.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg = /^(-)? if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite um número (o máximo de 14 dígitos inteiros e o máximo de 6 dígitos decimais)!", ThisInput); retornar falso; } return isNonnegative (valor, thisInput);} /** * Verifique o número (20,4) * /função isnum20p4 (value, thisInput) {// remover espaço tente {thisInput.value = thisInTein.value.trim (); } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg = /^(-)? if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite um número (o máximo de 16 dígitos inteiros e o máximo de 4 locais decimais)!", ThisInput); retornar falso; } retornar isbiggerZero (valor, este input);} /*** A quantidade de um único lote de margem inserido pelo fornecedor pode ser apenas um número inteiro positivo e só pode ser preciso para centenas de dígitos* /function iSdpcbzj (valor, thisInput) {// remover o espaço tentativa {thisInput.value.valuue = ThisInput) {// remover o espaço tentativa {thisInput.value = thisInput) {// Remover o espaço {thisInput.VUE = thisInTeue. } catch (e) {} value = value.trim (); if (value.Length == 0) {return true; } var reg =/^[1-9]/d*00 $/; if (! Reg.test (valor)) {writeValidateInfo ("Por favor, digite o valor da margem correta!", esse fato); retornar falso; } retornar true;} // Julgamento de que o ano inicial do relatório Ano de licitação não pode ser maior que a função do ano final ValidateYear (Startyear, Endyear, Flag) {if (startyear> endyear) {if (flag == 1) {alert ("O mês de partida não pode ser maior que o mês final"); retornar falso; } else {alert ("O ano inicial da licitação não pode ser maior que o ano final"); retornar falso; }} retornar true;}O exposto acima é tudo sobre este artigo, espero que seja útil para o aprendizado de todos.