首页 \ 问答 \ Bootstrap'form-group has-error'无法使用php代码[关闭](Bootstrap 'form-group has-error' not working with php codes [closed])

Bootstrap'form-group has-error'无法使用php代码[关闭](Bootstrap 'form-group has-error' not working with php codes [closed])

当我提交空字段时,输入不会变为红色并且不会打印错误消息。 当我使用此代码发送空字段时,如何显示错误消息并使输入框变为红色。

<?php 

  if ( !empty($_POST)) {
    require 'db.php';
    // validation errors
    $fnameError     = null;
    $lnameError     = null;
    $ageError       = null;
    $genderError    = null;

    // post values
    $fname  = $_POST['fname'];
    $lname  = $_POST['lname'];
    $age    = $_POST['age'];
    $gender = $_POST['gender'];

    // validate input
    $valid = true;
    if(empty($fname)) {
      $fnameError = 'Please enter First Name';
      $valid = false;
    }

    if(empty($lname)) {
      $lnameError = 'Please enter Last Name';
      $valid = false;
    }

    if(empty($age)) {
      $ageError = 'Please enter Age';
      $valid = false;
    }

    if(empty($gender)) {
      $genderError = 'Please select Gender';
      $valid = false;
    }

    // insert data
    if ($valid) {
      $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "INSERT INTO users (fname,lname,age,gender) values(?, ?, ?, ?)";
      $stmt = $PDO->prepare($sql);
      $stmt->execute(array($fname,$lname,$age,$gender));
      $PDO = null;
      header("Location: index.php");
    }
  }
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link   href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="row">
        <h3>Create a User</h3>
      </div>

      <form method="POST" action="create.php">
        <div class="form-group <?php echo !empty($fnameError)?'has-error':'';?>">
          <label for="inputFName">First Name</label>
          <input type="text" class="form-control" required="required" id="inputFName" value="<?php echo isset($fname)?$fname:'';?>" name="fname" placeholder="First Name">
          <span class="help-block"><?php echo isset($fnameError)?$fnameError:'';?></span>
        </div>
        <div class="form-group <?php echo !empty($lnameError)?'has-error':'';?>">
          <label for="inputLName">Last Name</label>
          <input type="text" class="form-control" required="required" id="inputLName" value="<?php echo isset($lname)?$lname:'';?>" name="lname" placeholder="Last Name">
          <span class="help-block"><?php echo isset($lnameError)?$lnameError:'';?></span>
        </div>
        <div class="form-group <?php echo !empty($ageError)?'has-error':'';?>">
          <label for="inputAge">Age</label>
          <input type="number" required="required" class="form-control" id="inputAge" value="<?php echo isset($age)?$age:'';?>" name="age" placeholder="Age">
          <span class="help-block"><?php echo isset($ageError)?$ageError:'';?></span>
        </div>
        <div class="form-group <?php echo !empty($genderError)?'has-error':'';?>">
          <label for="inputGender">Gender</label>
          <select class="form-control" required="required" id="inputGender" name="gender" >
            <option></option>
            <option value="male" <?php echo isset($gender)?'selected':'';?>>Male</option>
            <option value="female" <?php echo isset($gender)?'selected':'';?>>Female</option>
          </select>
          <span class="help-block"><?php echo isset($genderError)?$genderError:'';?></span>

        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-success">Create</button>
          <a class="btn btn btn-default" href="index.php">Back</a>
        </div>
      </form>

    </div> <!-- /row -->
  </div> <!-- /container -->

</body>
</html>

Inputs don't turn red and does not print the error messages when I'm submitting empty fields. How can I show the error messages and make the input boxes turn red when I'm sending empty fields with this code.

<?php 

  if ( !empty($_POST)) {
    require 'db.php';
    // validation errors
    $fnameError     = null;
    $lnameError     = null;
    $ageError       = null;
    $genderError    = null;

    // post values
    $fname  = $_POST['fname'];
    $lname  = $_POST['lname'];
    $age    = $_POST['age'];
    $gender = $_POST['gender'];

    // validate input
    $valid = true;
    if(empty($fname)) {
      $fnameError = 'Please enter First Name';
      $valid = false;
    }

    if(empty($lname)) {
      $lnameError = 'Please enter Last Name';
      $valid = false;
    }

    if(empty($age)) {
      $ageError = 'Please enter Age';
      $valid = false;
    }

    if(empty($gender)) {
      $genderError = 'Please select Gender';
      $valid = false;
    }

    // insert data
    if ($valid) {
      $PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "INSERT INTO users (fname,lname,age,gender) values(?, ?, ?, ?)";
      $stmt = $PDO->prepare($sql);
      $stmt->execute(array($fname,$lname,$age,$gender));
      $PDO = null;
      header("Location: index.php");
    }
  }
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link   href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="row">
        <h3>Create a User</h3>
      </div>

      <form method="POST" action="create.php">
        <div class="form-group <?php echo !empty($fnameError)?'has-error':'';?>">
          <label for="inputFName">First Name</label>
          <input type="text" class="form-control" required="required" id="inputFName" value="<?php echo isset($fname)?$fname:'';?>" name="fname" placeholder="First Name">
          <span class="help-block"><?php echo isset($fnameError)?$fnameError:'';?></span>
        </div>
        <div class="form-group <?php echo !empty($lnameError)?'has-error':'';?>">
          <label for="inputLName">Last Name</label>
          <input type="text" class="form-control" required="required" id="inputLName" value="<?php echo isset($lname)?$lname:'';?>" name="lname" placeholder="Last Name">
          <span class="help-block"><?php echo isset($lnameError)?$lnameError:'';?></span>
        </div>
        <div class="form-group <?php echo !empty($ageError)?'has-error':'';?>">
          <label for="inputAge">Age</label>
          <input type="number" required="required" class="form-control" id="inputAge" value="<?php echo isset($age)?$age:'';?>" name="age" placeholder="Age">
          <span class="help-block"><?php echo isset($ageError)?$ageError:'';?></span>
        </div>
        <div class="form-group <?php echo !empty($genderError)?'has-error':'';?>">
          <label for="inputGender">Gender</label>
          <select class="form-control" required="required" id="inputGender" name="gender" >
            <option></option>
            <option value="male" <?php echo isset($gender)?'selected':'';?>>Male</option>
            <option value="female" <?php echo isset($gender)?'selected':'';?>>Female</option>
          </select>
          <span class="help-block"><?php echo isset($genderError)?$genderError:'';?></span>

        </div>

        <div class="form-actions">
          <button type="submit" class="btn btn-success">Create</button>
          <a class="btn btn btn-default" href="index.php">Back</a>
        </div>
      </form>

    </div> <!-- /row -->
  </div> <!-- /container -->

</body>
</html>

原文:https://stackoverflow.com/questions/30837053
更新时间:2024-03-05 12:03

最满意答案

问题在于你的配置

@Bean
public SessionLocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(new Locale("en", "US"));
    return localeResolver;
}

这将构造名为sessionLocaleResolver的bean,但DispatcherServlet查找名称为localeResolver的bean。 如果未检测到它,它将使用默认值,即AcceptHeaderLocaleResovler

该解决方案非常简单,将您的方法重命名为localeResolver或在@Bean注释中包含name属性。

@Bean
public LocaleResolver localeResolver() { ... }

要么

@Bean(name="localeResolver")

The problem lies in your configuration

@Bean
public SessionLocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(new Locale("en", "US"));
    return localeResolver;
}

This constructs a bean with the name sessionLocaleResolver however the DispatcherServlet looks for a bean with the name localeResolver. If this isn't detected it will use the default, which is a AcceptHeaderLocaleResovler.

The solution is quite simple rename your method to localeResolver or include a name attribute in the @Bean annotation.

@Bean
public LocaleResolver localeResolver() { ... }

or

@Bean(name="localeResolver")

相关问答

更多
  • 我通常做的是拥有具有密钥和消息属性的自定义异常。 密钥是该错误的i18n密钥,该消息是默认消息。 所以在服务中: try{ some code } catch(SomeException e){ handleAppropriatly; throw new MyCustomException("error.foo","Some default message",e); } 该操作捕获消息并使用密钥将其正确添加到正确的位置(addActionError / addFieldError),从而允 ...
  • 既然你说这些问题只出现在RSpec测试中并且应用程序工作正常,那么我假设你期望这些URL采用/:locale/profile(.:format)的形式。 所以,如果您的应用程序中有类似以下路由范围的内容... 配置/ routes.rb中 scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do get 'profile', to: 'users#profile' # other routes end ...在控制器(可 ...
  • 对于任何类似的问题,这是解决方案 这里的问题是我使用的Basename路径,我必须在类路径中定义完整路径,而不使用区域后缀和文件扩展名(对于我来说,这是): @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource ...
  • 我找到了解决方案,我正确地给出了ResourceBundles的路径,下面是更改: @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("WEB-INF/classes/stat ...
  • 国际化(国际化)必须成为发展的一部分。 如果你等到最后,你需要重写部分代码。 考虑下列项目: 允许特定地区的号码和日期格式 外部化所有文本资源 创建一个能够很好地处理文本扩展的设计 允许公制与英制 ...(详情请参阅此链接 ) 所有这些项目在设计和开发过程中都需要不同的方法。 “先让英文先出来吧,以后我们会担心剩下的”,这是一个很大的(但很常见的)错误。 这种方法几乎肯定会导致更多的金钱,时间和挫折时间花在本地化时间到来之前。 I18N只是您在开发过程中需要应用的一套最佳实践。 即使您不打算本地化您的应用程 ...
  • 您可以使用PRG(POST-Redirect-GET)-pattern。 您必须通过POST请求进入您的页面。 并在您的应用程序创建控制器,将完成所有业务,而不是将用户重定向到另一个地址,而无需您的请求参与GET请求和另一个控制器。 没有用户更改会影响您的主题或语言。 You can use PRG(POST-Redirect-GET)-pattern. You will have to go on your page by POST request. And in your app create cont ...
  • 您配置了消息源以在类路径中查找属性文件(“classpath:messages”)。 您使用“/ WEB-INF / resources”的文件夹不是默认情况下类路径的一部分。 所以我的猜测是,如果你将属性文件移动到/ WEB-INF / classes(在提取的战争中)它应该工作。 或者您尝试将basename的属性从“classpath:messages”更改为“/ WEB-INF / resources / messages”。 但我不确定这是否有效。 延 you configured the mes ...
  • 问题在于你的配置 @Bean public SessionLocaleResolver sessionLocaleResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en", "US")); return localeResolver; } 这将构造名为sessionLocaleReso ...
  • 我粗略看了一下这个教程。 以下是我将如何做到这一点: 首先配置它: 在返回MessageSource实现的配置类中创建一个Bean。 @Bean public MessageSource messageSource() //The bean must be named messageSource. { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messa ...
  • @ControllerAdvice(annotations = RepositoryRestController.class) public class GenericExceptionHandler { @Autowired private MessageSource messageSource; @ExceptionHandler //if you don't use Exception e in method you can remove it , live only ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)