Onchange() validation is useful when you want to validate each of the input fields as soon as a user enters some value into it. Types of Form Validation in JavascriptĪs stated earlier, form validation can be done in two ways. If none of the validation conditions return true, the username will be valid and sent. Then, we checked the minimum and miximum length of the value and made the script display error message in case it meets one of those conditions. It will display an error message return false if there exist anyone of those, so no further blocks of javascript would run. Then, we checked for the presence of special characters stored in format in the field.
It will display an error message return false if there is no value, so no further blocks of javascript would run.
If no value is entered the function won't be triggered in this case but if the function was being triggered with a submit button then it would be needed. We stored it in a variable named username and stored the HTML special characters that we want to exclude from the username in another variable named format. Here, we created an input field to insert username. Username = document.getElementById('user_field').value ĭocument.getElementById("user-error").innerHTML = "Username must not be empty" ĭocument.getElementById("user-error").innerHTML = "Username must not contain any symbols" ĭocument.getElementById("user-error").innerHTML = "Username must not exceed 10 characters" "." and the last character as digits, we can create a combination of logical statement to validate email. Now, we've got the positioning values of three elements i.e. Finally, we counted the position of the last character in the value using value.length-1, which will give us the positioning of the last character in the string. symbol in the value using the same method. Then, we check the positioning of symbol using that counts the individual characters in the stored value as if they were in array. We added a input field which holds onChange, an event handler that triggers the function emailValidation.Īt first, we stored the input value in a variable named value. Lets have a look at the form validation example first. We can trigger the validation function with onchange or onsubmit event.
symbol to validate them.įorm validation can be divided into following categories. Basically in other fields, we check if there's any field empty but with input type email we can check the positioning of and. It's also used with server side languages though. Javascript is highly used in form validation especially in static sides where there's no server side script running.