For username validation in a form using JavaScript, I'm attempting to access the Label tag within the Form tag. If the Regex matches, then display an error in the Label; otherwise, hide it. However, when I try to modify the text in the text field, I encounter the following error:
Uncaught TypeError: can't access property "style", document.forms.form1.uNameError is undefined
Example code snippet:
<body>
<form name="form1">
// few code here
<div class="main">
<input type="text" id="uname" name="username" onchange="checkUsername()">
<label id="uNameError" style="color: red;">Incorrect name</label>
//few code here
</div>
</form>
<script>
var form=document.forms['form1'];
function checkUsername() {
let username=form["uname"].value.trim();
let validate= /[^a-zA-Z\s]/ig.test(username);
if(validate===true){
form["uNameError"].style.display="inline";
}else {
form["uNameError"].style.display="none";
}
}
</script>
</body>
Is there a way to effectively reuse the form variable in this scenario?