I searched a lot on this forum to solve this issue I have, but have not succeeded thus far. I have a form with several <input>
sections. In this form I have a password field and a confirmation password field which needs to be validated with the first password. Here is HTML code example:
<input
title="Password should contain at least 6 characters or numbers" type="password"
pattern=".{6,}"
name="RegisterForm[password]"
onchange="this.setCustomValidity(this.validity.patternMismatch ? this.title : ''); if(this.checkValidity()) form.RegisterForm[password2].pattern = this.value;"
placeholder="Password..."/>
<input
title="Please enter the same Password as above"
type="password"
pattern=".{6,}"
name="RegisterForm[password2]"
onchange="this.setCustomValidity(this.validity.patternMismatch ? this.title : '');"
placeholder="Confirm Password . . ."/>
Both inputs have a name with square brackets, e.g. "RegisterForm[password]"
. If I use name attributes without the brackets the validation works, if I use it with brackets, the validation does not work. Any ideas how to overcome the square bracket issue in the name attribute without losing the square brackets?
If I would replace the name attributes with "password1"
and "password2"
, then everything works as it supposed to do.
If anyone has the solution, please help me out! :-).
First of all I think this is not good practice to put much code inside
on-
event attributes. As for me, I prefer to define some functions in javascript source file and use them rather than put complex expressions into attributes.Anyway, the issue is that
form.RegisterForm[password2].pattern
is wrong way to access your input element. In this case firstform
object is looked up. Then interpreter tries to look upRegisterForm
property. Square brackets is another way to access object's property, but it requires a string. In your case there goespassword2
identifier rather that string literal, and I believe it will try to read the value of variable with same name and look up property inRegisterForm
depending on result. So entire expression is invalid and likely will fail early atRegisterForm
step.But you still can access your input by name containing square brackets, for example using
querySelector()
function:Following code snippet works as expected: if entered password is invalid it sets custom validity message to password input, otherwise it sets empty validity message and updates pattern attribute of confirmation input.
P.S. structure your code, this will help you in future.