2017-05-27 32 views
0

我想在JavaScript中驗證我的引導形式與正則表達式。我已經開始使用JavaScript,但不知道用正則表達式繼續驗證的正確方法。我試圖在提交之前驗證表單中的每個輸入。驗證表格與正則表達式,而使用Javascript

如果有人可以幫我解決我的問題,將不勝感激。

非常感謝您提前。 在javascript中沒有jQuery,請

約翰西蒙斯

HTML(這是我的HTML引導形式)

<div class="col-md-6"> 
     <div class="well well-sm"> 
      <form class="form-horizontal" id="form" method="post" onsubmit="return validerForm(this)"> 
       <fieldset> 
        <legend class="text-center header">Contact</legend> 
        <div class="form-group"> 
         <div class="col-md-10 col-md-offset-1"> 
          <input id="lastName" name="LN" type="text" placeholder="Nom" autofocus class="form-control"> 
         </div> 
        </div> 
        <div class="form-group"> 
         <div class="col-md-10 col-md-offset-1"> 
          <input id="firstName" name="FN" type="text" placeholder="Prenom" class="form-control"> 
         </div> 
        </div> 

        <div class="form-group"> 
         <div class="col-md-10 col-md-offset-1"> 
          <input id="email" name="email" type="text" placeholder="Courriel" class="form-control"> 
         </div> 
        </div> 

        <div class="form-group"> 
         <div class="col-md-10 col-md-offset-1"> 
          <input id="phone" name="phone" type="text" placeholder="Téléphone" class="form-control"> 
         </div> 
        </div> 

        <div class="form-group"> 
         <div class="col-md-10 col-md-offset-1"> 
          <textarea class="form-control" id="message" name="Message" placeholder="Entrez votre message. Nous allons vous répondre le plus tôt que possible." rows="7"></textarea> 
         </div> 
        </div> 

        <div class="form-group"> 
         <div class="col-md-12 text-center"> 
          <button type="submit" class="btn btn-primary btn-lg">Submit</button> 
          <input class="btn btn-primary btn-lg" type="reset" onclick="clearForm()" value="Clear"> 
         </div> 
        </div> 
       </fieldset> 
      </form> 
     </div> 
    </div> 

的Javascript(這是我的javascript我regexs,我還想着做一個函數,將驗證與正則表達式輸入的每個值)

var nameregex = /(^[A-Z][a-z]{1,24})+$/; 
var emailregex= /^([A-Za-z])([A-Za-z0-9])+\@([a-z0-9\-]{2,})\.([a-z]{2,4})$/; 


function validerForm(form) { 
    window.onload = function(){ 
     document.getElementById('lastName').focus(); 
    } 

    var valName = Formulaire.name.value; 
    var valFirst = Formulaire.firstname.value; 
    var valEmail = Formulaire.email.value; 

    var nameValide = validationName(valName); 
    var firstValide = validationFirstName(valFirst); 
    var emailValide - validationEmail(valEmail); 


} 

function validationName(valName){ 
    if(nameregex.test(valName) == true){ 

    }else{ 

    } 
} 

function clearForm() { 
    document.getElementById("form").reset(); 
} 

回答

0

您可能會使用s tring.match()

i.e.: if (valEmail.match(emailregex)) { do stuff!; } 
+0

我該如何添加消息錯誤下的輸入是殘疾人? –

+0

簡單地使用否定(NOT)(!),所以與上面的例子相同: 'if(!valEmail.match(emailregex)){在這裏處理; }' – GwadaKing