Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
James Barrett
13,253 PointsClient-Side validation display issue
I am relatively new to JavaScript and I am trying to achieve client-side validation on my registration form. The goal is to when the user presses submit button, errors are set to visibility: visible. However this does not work. What is wrong with my code?
HTML:
<form id="register" name="register" action="#" method="post">
<label for="forename">Forename</label>
<input type="text" id="forename" name="user_forename" placeholder="John" required>
<span id="errorforename" class="error">First name is required</span>
<button type="submit" value="Submit" onclick="validate();">Register</button>
</form>
CSS:
.error {
color: red;
font-style: italic;
font-size: 17px;
visibility: hidden;
}
JavaScript:
<script type="text/javascript">
function validate() {
var errorname = document.getElementById("errorforename");
var user_forename = document.register.user_forename;
if (user_forename === "") {
errorforename.style.visibility = "visible";
}
}
</script>
1 Answer
rydavim
18,815 PointsYou just need one small change. You're currently trying to use an element instead of the value.
// On this line...
var user_forename = document.register.user_forename;
// you want to use the value of user_forename instead.
var user_forename = document.register.user_forename.value;
That should do it, but let me know if you have any questions. Happy coding! :)
James Barrett
13,253 PointsJames Barrett
13,253 PointsAwesome, thank you for your response