在使用Javascript或Jquery单击“提交”按钮时,有人可以建议文本框进行客户端正则表达式验证吗?
答案 0 :(得分:0)
在您的HTML中添加jQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
添加喜欢的HTML示例
<h2>Example 1:</h2>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email"></input>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
您的Javascript代码
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var password = $('#password').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
}
if (email.length < 1) {
$('#email').after('<span class="error">This field is required</span>');
} else {
var regEx = /^[A-Z0-9][A-Z0-9._%+-]{0,63}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/;
var validEmail = regEx.test(email);
if (!validEmail) {
$('#email').after('<span class="error">Enter a valid email</span>');
}
}
if (password.length < 8) {
$('#password').after('<span class="error">Password must be at least 8 characters long</span>');
}
});
});