首页 > 解决方案 > 如何在输入文本字段中只允许字符串

问题描述

如何使用 rails haml 表单仅允许在 text_field 上输入字符串。

.field
  = f.label "agent_name"
  = f.text_field :agent_name, :required => true,:id=>"agent_name_validation"
  $("#agent_name_validation").keypress(function(event) {
    var string = /^[a-z]+$/i;
    if(event.which != string){
      return false;
    }
  });

标签: javascriptruby-on-railsrubydom-eventshaml

解决方案


使用以下 Jquery 函数从文本字段中删除数字

$("#agent_name_validation").keyup(function(e) {
  // Our regex
  // a-z => allow all lowercase alphabets
  // A-Z => allow all uppercase alphabets
  var regex = /^[a-zA-Z]+$/;
  // This is will test the value against the regex
  // Will return True if regex satisfied
  if (regex.test(this.value) !== true)
  //alert if not true
  //alert("Invalid Input");

  // You can replace the invalid characters by:
    this.value = this.value.replace(/[^a-zA-Z]+/, '');
});

推荐阅读