我有一个简单的表单,可以一次显示2个错误代码,但是我只需要显示一个即可(请参阅下文)。如果用户输入无效电子邮件,则#1应该是唯一显示的电子邮件,无效性由表单输入文本required pattern=...
确定。如果电子邮件是有效,则错误#2应该是唯一可见的错误。它是由PHP结果产生的-该PHP文件通过表单html文件中的ajax调用,并返回显示为错误#2的结果。
我的问题:我如何应用IF语句或类似语句来确定是否
表单的输入字段的模式是否满足。如果不满意(无效),那么我们可以通过以某种方式更改CSS来使它的字体大小为0px,这只会使#2可见。如果满意,那么我们可以继续以某种方式隐藏错误#2的div。
这是表格(错误#2的隐藏div“formResponse”):
<form id="loginform" name="loginform" method="POST" class="login" action="#">
<input name="emailaddy" id="emailaddy" type="email" class="feedback-input" placeholder="My Email" required pattern="[a-z0-9!#$%&'*+/=?^_`{|}~)" required title="Invalid Email"/>
<div id="formResponse" style="display: none;"></div>
<button type="submit" name="loginsubmit" class="loginbutton">Login</button>
</form>
和CSS:
div.error, div.error-list, label.error, input.error, select.error, textarea.error {
color: #D95C5C!important;
border-color: #D95C5C!important;
font-size: 18px;
}
更新了AJAX(通过雷吉的答案)-注意:我认为
if(ema == null || ema == '')
不起作用,因为即使用户输入乱码,它仍然会显示两个错误。但是,如果我将其更改为if(ema == 'a')
,它将正确隐藏formResponse
div并仅显示label.error。如果字段无效/为空,我需要它来隐藏formResponse
-但null似乎不起作用。另外,else
函数不起作用,这意味着label.error
div由于某种原因不会隐藏。也许null
应该用正则表达式检查代替?更新的AJAX:为什么将“hello@example.com”视为空?
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
success:function(result){
if(result === "redirect"){
window.location.replace("http://www.example.com/login/private.php");
}
else{
//var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
var email = $('#emailaddy').val();
var pattern = ".+\\@@.+\\..+";
var valid = email.match(pattern);
alert(valid);
if (valid == null) {
}
else {
$("#formResponse").html("That email address is not registered.").show();
}
}
}
})
});
});
</script>
最佳答案
在ajax中,如果无效,您可以检查电子邮件并阻止其发送到服务器:
var ema = $('#useremail').val();
if(ema == null || ema == '' //or whatever)
{
$('.error1').show();
$('.error1').html('Nope');
$('.error2').hide();
return;
}
else{
//continue with ajax
然后处理从php返回的所有错误,例如:
success: function(responseText) {
if(responseText == "1") {
$('.error1').hide();
$('.error2').show();
$('.error2').html(//the error msg);
}
关于php - 如何根据表单字段是否有效来更改CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29224485/