这不适用于Jquery最新版本的CDN(内容交付网络):
Validating HTML forms is a very important aspect during form submission. jQuery helps in validating forms at client side. The following steps are required to validate a form.
Step 1: Create a Simple HTML Form
To create the form use the following code.
<h1>Fill out your information</h1>
<form id="regForm" method="post">
<input type="text" name="fullname" id="fullname" placeholder="Your Full Name"/>
<input type="text" name="email" id="email" placeholder="Email ID"/>
<input type="text" name="mobileno" id="mobileno" id="mobileno" placeholder="Mobile Number" maxlength="10"/>
<input type="text" name="address" id="address" placeholder="Address"/>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
<input type="password" name="repassword" id="repassword" value="" placeholder="RetypePassword"/>
<button name="submit" type="button" id="btnvalidate">Click to Submit</button>
</form>
This is the form view of the above code
第2步:包括最新的jQuery库 可以从https://jquery.com/下载最新的jquery库。将最新的库添加到HTML页面的顶部。
第3步:添加函数以验证表单 在HTML表单的“”标签内添加jquery函数。使用以下代码验证表单。
<script type="text/javascript">
//Find the values added in form using the id of each fields. The ".val()" function finds the value added in the form fields.
var fullname = $('#fullname').val();
var address = $('#address').val();
var mobileno = $('#mobileno').val();
var email = $('#email').val();
var indexat = email.indexOf("@"); //Index of "@" in the email field
var indexdot = email.indexOf("."); //Index of "." in the email field
var password = $('#password').val();
var repassword = $('#repassword').val();
//Function will execute when the button "Click to Submit" is clicked.
$('#btnvalidate').click(function() {
//Blank field validation of fullname, mobile no and address. The function will generate an alert message if "fullname" or "mobile no" or "address" field is blank
if(fullname == '')
{
alert('Please enter your Full Name');
$('#fullname').focus(); //The focus function will move the cursor to "fullname" field
}
else if(address == '')
{
alert('Please enter your Address');
$('#address').focus();
}
else if(mobileno == '')
{
alert('Please enter your Mobile Number');
$('#address').focus();
}
//Validation of valid email address. The function will generate an alert message if "email" field is blank or incorrect
else if(indexat < 1 || (indexdot-indexat) < 2)
{
alert('Please enter a valid Email Id');
$('#email').focus();
}
//Validation of password. The function will generate an alert message if "password" field is not same as "retype password".
else if(password == '' && password != repassword)
{
alert('Password and Retype password donot match');
$('#repassword').focus();
}
});
</script>
答案 0 :(得分:0)
您必须在click事件中获取所有文本字段值。