Should be email as Variable, not as String
var email = $('#my-input').val();
if ( reg.test(email) ) {
Here's a slight remake with the mentioned fix.
It uses a CSS class to determine the styles. JS is only used to toggle that has-error class from the common parent label element.
It also doesn't uses IDs. data-validate is a far more flexible option!
const has = {
value: (val) => val.trim().length > 0,
email: (val) => /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(val),
// add more validators here
};
jQuery(function($) { // DOM ready and $ alias inn scope
function validate() {
const isValid = has[this.dataset.validate](this.value);
$(this).closest("label").toggleClass("has-error", !isValid);
}
$("[data-validate]").on("focusout", validate);
});
/*QuickReset*/ *,*::before,*::after{margin:0; box-sizing:border-box;}
body {font:16px/1.6 sans-serif;}
label {
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
margin: 5px;
border: 2px solid transparent;
}
label input {
flex: 1;
}
label.has-error {
border: 2px solid red;
border-image-slice: 1;
border-image-source: linear-gradient(to right, red, fuchsia);
}
label .error {
color: red;
display: none;
}
label.has-error .error {
display: inline-block;
}
<label>
<span class="placeholder">Name:</span>
<input type="text" name="name" data-validate="value">
<span class="error">Name cannot be empty</span>
</label>
<label>
<span class="placeholder">Email:</span>
<input type="text" name="email" data-validate="email">
<span class="error">Invalid Email address</span>
</label>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
PS: makes no sense to use "green" colors to mark something OK in UI. It's the same logic in which you would never show an alert box saying "Hey! Your email is correct!". Users presume it's correct if not marked otherwise.