基本验证- 这是一个确保所有必填字段都已填写或未填写的过程。
数据格式验证- 顾名思义,就是检查输入的数据是否正确的过程。我们必须包含适当的逻辑来测试数据的正确性。
<!DOCTYPE html> <html> <head> <title>Example of Basic form Validation</title> <script> function validateBasic() { var name1 = document.basic.name.value; var qual1 = document.basic.qual.value; var phone1 = document.basic.phone.value; if (name1 == "") { alert("Name required"); return false; } if (qual1 == "") { alert("Qualification required"); return false; } if (phone1 == "") { alert("Mobile number is required"); return false; } } </script> </head> <body> <center> <h1>Basic Form Validation</h1> <form name="basic" action="#" onsubmit="return validateBasic()"> <table cellspacing = "2" cellpadding = "2" border = "1"> <tr> <td>Name: </td> <td><input type="text" name="name"></td> <tr> <tr> <td> Qualification: </td> <td><input type="text" name="qual"></td> </tr> <tr> <td>Phone no.:</td> <td><input type="text" name="phone"></td> </tr> </table> <input type="submit" value="Submit"> </form> <p id="d1"></p> </center> </body> </html>
<!DOCTYPE html> <html> <head> <title>Example of Basic form Validation</title> <script> function validateBasic() { var name1 = document.basic.name.value; var qual1 = document.basic.qual.value; var phone1 = document.basic.phone.value; var id = document.basic.em.value; if (name1 == "") { alert("Name required"); return false; } if(name1.length<5){ alert("Username should be atleast 5 characters"); return false; } at = id.indexOf("@"); dot = id.lastIndexOf("."); if (at < 1 || ( dot-at < 2 )) { alert("Incorrect Email-ID") return false; } if (qual1 == "") { alert("Qualification required"); return false; } if (phone1 == "") { alert("Mobile number is required"); return false; } if(phone1.length<10 || phone1.length>10){ alert("Mobile number should be of 10 digits"); return false; } } </script> </head> <body> <center> <h1>Basic Form Validation</h1> <form name="basic" action="#" onsubmit="return validateBasic()"> <table cellspacing = "2" cellpadding = "2" border = "1"> <tr> <td>Name: </td> <td><input type="text" name="name"></td> </tr> <tr> <td>Email: </td> <td><input type="email" name="em"></td> </tr> <tr> <td> Qualification: </td> <td><input type="text" name="qual"></td> </tr> <tr> <td>Phone no.:</td> <td><input type="number" name="phone"></td> </tr> </table> <input type="submit" value="Submit"> </form> <p id="d1"></p> </center> </body> </html>