简体   繁体   English

javascript:正则表达式问题

[英]javascript : problem with regular expression

I'm trying to validate the value of an input text field with the following code: 我正在尝试使用以下代码来验证输入文本字段的值:

function onBlurTexto(value) {

    var regexNIT = "([a-zA-z]|[0-9]|[&#,@.ÑñáéíóúÁÉÍÓÚ\|\s])";

    regexCompilado = new RegExp(regexNIT);

    if (!(regexCompilado.test(value))) {
        alert("Wrong character in text :(");
        return false;
    } else {
        return true;
    }
}

But when i enter this text: 但是当我输入此文本时:

!65a !65A

the function returns true (as you can see, the "!" character does not exist in the regular expression) 该函数返回true(如您所见,正则表达式中不存在“!”字符)

I'm not an expert in regular expressions, so i think i am missing something in the building of this reg.exp. 我不是正则表达式方面的专家,所以我认为我在此reg.exp的构建中缺少某些内容。

How can i put this regular expression to work? 我该如何使用此正则表达式?

Thanks in advance. 提前致谢。

EDIT 编辑

i am so sorry ... i should remove the references to the variable "regexpValidar" before posting the issue. 我很抱歉...我应该在发布问题之前删除对变量“ regexpValidar”的引用。 I modified the sample. 我修改了样本。 Thanks @TecBrat 谢谢@TecBrat

You should provide the start (^) and end ($) flags to your regex. 您应该为正则表达式提供开始(^)和结束($)标志。 Now you are matching 65a since you have alternate sets. 现在,您有65a,因为您有备用组。

This should work /^([a-zA-z]|[0-9]|[&#,@.ÑñáéíóúÁÉÍÓÚ\\|\\s])+$/g 这应该可以工作/^([a-zA-z]|[0-9]|[&#,@.ÑñáéíóúÁÉÍÓÚ\\|\\s])+$/g

Demo: https://regex101.com/r/zo2MpN/3 演示: https : //regex101.com/r/zo2MpN/3

RegExp.test looks for a match in the string, it doesn't verify that the whole string matches the regex. RegExp.test在字符串中查找匹配项,它不会验证整个字符串是否与正则表达式匹配。 In order to do the latter, you need to add start and end anchors to your regex (ie '^' at the start and '$' at the end, so you have "^your regex here$"). 为了进行后者,您需要在正则表达式中添加开始和结束锚点(即,在开始处为“ ^”,在结束处为“ $”,因此您有“ ^ your regex here $”)。

I also just noticed that your regex is currently matching only one character. 我还注意到您的正则表达式当前仅匹配一个字符。 You probably want to add a '+' after the parens so that it matches one or more: 您可能想在括号后面添加一个“ +”,使其与一个或多个匹配:

"^([a-zA-z]|[0-9]|[&#,@.ÑñáéíóúÁÉÍÓÚ\|\s])+$"

This is wrong. 错了 the variable you use doesn't has anything. 您使用的变量没有任何内容。 Try this instead. 试试这个吧。

var regexCompilado = new RegExp(regexNIT);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM