Adding an event hadler using DOM and addEventListener

I’m trying to add a text input to receive an email address. Then add an event handler using the DOM and addEventListener for the blur event. In the handler call the ValidateEmail event with the text entered. Use the event parameter to access the text box in the Target property. Use it’s Value to get the email address. If the return value of validate email is false change the background style of the text box to red. If it’s valid change it to “transparent”. I’m not sure if I’m close. Can anyone give me any pointers?

<!Doctype html>
<html>
<!--Header-->
<head>	
    <title>JavaScript Assignment 4- Jasmine Lusty</title>
    <!--can contain javascript imports but page javascipt should be at the bottom of the body-->
</head>
<!--Body-->
<body>
 
<!---- Email Html--->
<h4>Email Validation!</h4>
	<label for="inputEmail">Enter your email:</label>
	<input type="email" id="input" name="email">

<!--javascript code-->

<script type="text/javascript">
		var emailPattern = /[\w-\.]+@([\w-]+\.)+[\w-]{2,4}/;

		
input.onblur = function() {
  if (!input.value.includes('/[\w-\.]+@([\w-]+\.)+[\w-]{2,4}/')) {
    input.classList.add('invalid');
    document.addEventListener("blur", function(){ document.style.backgroundColor = "transparent";});
  } else{
	document.addEventListener("blur", function(){ document.style.backgroundColor = "red";});  
  }
};

input.onfocus = function() {
  if (this.classList.contains('invalid')) {
    // remove the "error" indication, because the user wants to re-enter something
    this.classList.remove('invalid');
    error.innerHTML = "";
  }
};
	

		validateEmail(input)

</script>
<!--end of scripts-->


</body>
</html>

well i imagine that’s throwing you an error because you havent declared ‘input’.

Validating an email is always a notoriously difficult thing to do.

Regex tests should be checked with .test(), not includes.

you’ll find it easier to control this by defining your CSS for the ‘invalid’ class, and then simply adding/removing the invalid class from the elements as necessary. Define your invalid class to have a background color of red, and then you don’t need to attach other event listeners, you can just let the browser’s internal renderer handle the statechange.

Also, you may want to consider implementing some browser-builtin validation, but if your form needs to contend with pre-HTML5 browsers or you’re doing this as an exercise of javascript, perhaps not the desired solution.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.