【问题标题】:Validate input with regular expression for universal alphabets in javascript使用正则表达式验证 javascript 中通用字母的输入
【发布时间】:2018-07-03 05:25:31
【问题描述】:

我有一个form validator by AntonLapshin,我正在尝试验证一个非空输入字段,该字段只能使用字母、空格和 - 和'。字母可以是 a-z、A-Z 和欧式字母 æÆøØåÅöÖéÉèÈüÜ 等。See this for more details

这是我正在做的事情:

method  : function(input) {
    return input.value !== ''
        && input.value === /^[a-zA-Z'\- \u00c0-\u017e]+$/
}

这里应该匹配:Åløæ-Bond Mc'Cool

但失败:123-Bond Mc'C@o!

当我在regex tester 中运行^[a-zA-Z'\- \u00c0-\u017e]+$ 时,它工作得非常好,但在我的脚本中,它没有进行验证并引发无效输入错误。

我做错了什么?

【问题讨论】:

  • 从你的脚本中得到错误会很有帮助
  • 你的脚本有什么错误?
  • 我的脚本中没有语法错误。这只是正则表达式模式不起作用。

标签: javascript regex validation


【解决方案1】:

我更喜欢使用RegExp。你还需要做return pattern.test(input)

这会起作用:)

var test1 = "Åløæ-Bond Mc'Cool";
var test2 = "123-Bond Mc'C@o!";

var pattern = new RegExp(/^[a-zA-Z'\- \u00c0-\u017e]+$/);

function regextest(input) {
    return input !== '' && pattern.test(input)
}

console.log(regextest(test1))
console.log(regextest(test2))

【讨论】:

  • 使用RegExp 不是必须的,但pattern.test 是;)
  • 真的吗? @Zim 哇,我从来没有意识到 :) 每天都学习新东西 ;) 更新
【解决方案2】:

修改你的函数以使用正则表达式进行测试

var pattern = /^[a-zA-Z'\- \u00c0-\u017e]+$/

var method = function(input) {
  return input !== '' &&
    pattern.test(input)
}

//your sample strings
console.log(method("Åløæ-Bond Mc'Cool"))
console.log(method("123 - Bond Mc 'C@o!"))

【讨论】:

  • 不知道这个答案怎么有 2 个赞成票。它对我不起作用@CodeMonk
【解决方案3】:

我为我的问题找到了一个更简单的解决方案:

method  : function(input) {
    return input.value !== '' && /^[a-zA-Z'\- \u00c0-\u017e]+$/.test(input.value)
}

问题是,在&& 运算符之后,我检查的是输入值(在正则表达式检查中是错误的)而不是布尔值。

此解决方案完美运行,不会造成混乱。

【讨论】:

  • 你是对的。我只是指我自己的问题的可读性
猜你喜欢
  • 1970-01-01
  • 2019-01-07
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
相关资源
最近更新 更多