表单的 PHP 错误

标签 php html css

<分区>


想改进这个问题吗? 通过 editing this post 添加细节并澄清问题.

关闭 7 年前

当收到错误代码指示时,我想将我的 div 布局保留在我的网站上。事情是我不希望多个错误有两个单独的 css/div 布局。这是我到目前为止得到的:

if(!preg_match($email_exp,$email_from)) {
  $error_message .= '<font color="blue">The Email Address you entered does not appear to be valid.<br /></font>';
}

$string_exp = "/^[A-Za-z .'-]+$/";

if(!preg_match($string_exp,$first_name)) {
  $error_message .= 'The First Name you entered does not appear to be valid.<br />';
}

if(!preg_match($string_exp,$last_name)) {
  $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}

if(strlen($comments) < 2) {
  $error_message .= 'The Comments you entered do not appear to be valid.<br />';

我希望它们都在一个页面上打开并具有相同的布局。如果有多个错误,我希望它们不要每个都有单独的代码。我该怎么做?

最佳答案

所以我认为您要求单个 div 来显示任何错误,如下所示:

<div id="errors">
    <?php echo (!empty($error_message) ? $error_message : ""); ?>
</div>

但是如果您希望错误显示在与表单相同的页面上,最好使用 Javascript 来实现。在您的页面上放置类似这样的内容:

<form>
    Sample: <input id="sample" type="text" onKeyUp="validateInputs()">
    <button type="button">Button Text</button>
</form>
<div id="error-div"></div>

<script>
    function validateInputs() {
    var errorMessage = '';
    var sampleText = document.getElementById('sample').value;
    if( !sampleText || sampleText.length < 4 ) {
        errorMessage = 'input "Sample" must be as least 4 chars in length';
    }
    if( errorMessage.length > 0 ) {
        document.getElementById('error-div').innerHTML = errorMessage;
    } else {
        document.getElementById('error-div').innerHTML = 'no errors';   
    }
  }
</script>

这是一个有效的 jsfiddle example .

关于表单的 PHP 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35512218/

上一篇:html - 如何让聊天从屏幕底部出现?

下一篇:html - Bootstrap 模态对话框关闭屏幕,背景为白色

相关文章:

php - 在 foreach 循环期间将查询结果插入 php 字符串

php - 三元 foreach 嵌套在 if/else 中

javascript - window.location.href 在弹出窗口中不起作用

jquery - JQuery 中的水平动画

javascript - 如何在向下滚动时实现 float div

html - 调整内容 : space-between not applying on nested flex box

php - 如何管理从多个表中选择大量数据?

php - 在 ArrayObject 中循环和取消设置时 foreach 出现意外行为。一个项目被忽略

javascript - 将同一类别的单词放在一起的有序列表

css - 忽略 :hover in a specific class