简体   繁体   English

表单验证正则表达式和DOM:什么是在表单验证中实现正则表达式的最佳方法

[英]Form validation regex and DOM: What would be the best way to implement regex in a form validation

Form validation regex and DOM: What would be the best way to implement regex in a form validation? 表单验证正则表达式和DOM:在表单验证中实现正则表达式的最佳方法是什么?

Im currently doing this, but when I validate it's not matching the values: 我目前正在这样做,但是当我验证它与值不匹配时:

if(this.value.length > 0 && this.value === /^[a-zA-Z]+$/ );

Thank You in advance! 先感谢您!

you need to use the test() method. 您需要使用test()方法。

var patt = /^[a-zA-Z]+$/; //define your RegEx

    if(this.value.length > 0 && patt.test(this.value)){ //check if this.value is longer than one character AND matches your RegEx
           //do something
     };

See http://www.w3schools.com/jsref/jsref_regexp_test.asp 参见http://www.w3schools.com/jsref/jsref_regexp_test.asp

Why you code does not mathing any values? 为什么您的代码没有数学任何值? Because you used typewise equality test === . 因为您使用了按类型的相等性测试=== In dynamic types of JavaScript world it states for: test types of those values if they are the same and then test values if they are equal. 在JavaScript世界的动态类型中,它声明:如果这些值的类型相同,则测试它们的类型,如果它们相等,则测试它们的值。 So when you were trying to test in that way values of some textboxes, which are strings 因此,当您尝试以这种方式测试某些文本框(即字符串)的值时

typeof('a')

this code will yield "string" because of 'a' is indeed a string. 该代码将产生“字符串”,因为“ a”确实是字符串。 But: 但:

typeof(/^[a-zA-Z]+$/)

this will yield "object". 这将产生“对象”。 As you see typewise equality test will always return false when you are trying compare string to object. 如您所见,当您尝试将字符串与对象进行比较时,类型式相等性测试将始终返回false。

That is for testing equality of objects and its values. 那是为了测试对象及其值的相等性。 For regex see 'bam' answer. 对于正则表达式,请参见“ bam”答案。

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

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