1

I am very new to JS and HTML, so my apologies. I have run into trouble trying to validate input into a form field with the pattern='' attribute. Although it catches invalid input and gives the appropriate error message, subsequent modifications of the input do not change the error message. For example,

pattern="[a-zA-Z]" will produce the appropriate message if the user enters "testing2" into the field. But if the user edits the entry to "testing" I still get a validation error.

In trying to figure this out, I tried to log the field input to the console. So, in the HTML:

<input class="dest_one_key" name="dest_one_key" type="text" id="dest_one_key" required="" placeholder="Work">

and then:

<script> var v = document.getElementById('dest_one_key').value; document.getElementById('dest_one_key').addEventListener('change', function() { console.log(Value: ${v}); }); </script>

...which yeilds

"Value: "

in the console. So the form does not seem to be capturing the users input.

What I'm doing wrong with respect to: 1) Not being able to properly register that the user has a valid input after an invalid input 2) logging the value of the field to the console?

4
  • I think what you want its something like this: stackoverflow.com/questions/20287650/… Commented Oct 14, 2017 at 20:46
  • Here is a simple example of it: jsbin.com/natociy/2/edit?html,js,console,output Commented Oct 14, 2017 at 21:03
  • Yes! That fixed the problem with the page accepting user edits. (I searched all over the place, and this was never mentioned for the regex). Why am I running into problem 2)? Commented Oct 14, 2017 at 21:04
  • if you want to log the value you can use keyup event to log each time the user inputs something new. here is an example: jsbin.com/natociy/4/edit?html,js,output Commented Oct 14, 2017 at 21:28

1 Answer 1

2

Since your script run only once, the v variable will be empty. You need to change it over time using event.target.value in your event. Like this:

var v;

document.getElementById('dest_one_key').addEventListener('change', function(event) {
    v = event.target.value;
    console.log('Value: ' + v);
});
<input class="dest_one_key" name="dest_one_key" type="text" id="dest_one_key" required="" placeholder="Work">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.