简体   繁体   中英

javascript form validation issue

for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.

  
  <form name="form" onsubmit="return formValidation()" action="submit.html"> lastname :<input type="text" name="lastname" id="lastname"> </input><br><br> <label>NIC Number:</label> <input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br> <input id="submit" type="submit" name="submit" id="submit"> 

You can add a custom validation: JSFiddle

Code

 function validateNIC() { var nic = document.getElementById("NIC").value; var lname = document.getElementById("lastName").value; var valid = true; if (nic.length != 14) { console.log("Length must be 14 characters"); } else if (nic[0] != lname[0]) { console.log("First Character of both input should be same"); } else{ console.log("Valid") } } 
 <input type="text" id="lastName"> <input type="text" id="NIC" maxlength=14> <button onclick="validateNIC()">validate</button> 

try like this using charAt .

 var x = 'some string';//value from first field var y="s2324343353";//value from nic if(x.charAt(0) == y.charAt(0)){ alert("first character is same"); }// alerts 's' 

I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.

 function formValidation() { var ln = document.getElementById("lastname"); var nic = document.getElementById("NIC"); if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) { alert("NIC first character not acceptable."); return false; } else { return true; } } 
 <form name="form" onsubmit="return formValidation()" action="submit.html"> lastname : <input type="text" name="lastname" id="lastname"> </input> <br> <br> <label>NIC Number:</label> <input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input> </br> </br> <input id="submit" type="submit" name="submit" id="submit"> 

 function formValidation() {
        var lastname = $('#lastname').val();
        var NIC = $('#NIC').val();
        if (lastname.charAt(0) != NIC.charAt(0)) {
         return false;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM