jeudi 19 mars 2020

html5 input pattern attribute vs test()?

Run the code snippet and compare the results for the second pattern.

Why is it a match with .test() but not a match in a pattern attribute?

It seems that the pattern attribute requires it to match the entire text, which can be seen in test set B.

Is there a way to make the pattern attribute behave more like test set A?

Why is it designed this way?

var tst = '123asdf456'
var a = []
var b = []

a[0] = (/.*asdf.*/).test(tst)
a[1] = (/asdf/).test(tst)
a[2] = (/^asdf$/).test(tst)
console.log('Test set A:',a[0],a[1],a[2])

b[0] = ((/.*asdf.*/).exec(tst)||[])[0]==tst
b[1] = ((/asdf/).exec(tst)||[])[0]==tst
b[2] = ((/^asdf$/).exec(tst)||[])[0]==tst
console.log('Test set B:',b[0],b[1],b[2])
input:invalid {background-color: pink;}
<input pattern=".*asdf.*" value="123asdf456"/>
<input pattern="asdf" value="123asdf456"/>
<input pattern="^asdf$" value="123asdf456"/>

Aucun commentaire:

Enregistrer un commentaire