简体   繁体   中英

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?

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.

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

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. 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. 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.

That is for testing equality of objects and its values. For regex see 'bam' answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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