JavaScript - tutorial - 16 - forms

revision:


Content

JavaScript form validation JavaScript validation API Forms examples


JavaScript form validation

top

HTML form validation can be done by JavaScript, as JavaScript is often used to validate numeric input.

Examples

Please input a number between 1 and 10:


code:
                    <div class="spec">
                        <p>Please input a number between 1 and 10:</p>
                        <input id="numb">
                        <button type="button" onclick="inputNum()">Submit</button><br>
                        <a id="demo"></a>       
                    </div>
                    <script>
                        function inputNum() {
                            var x, text;
                            x = document.getElementById("numb").value;
                            if (isNaN(x) || x < 1 || x > 10) {
                            text = "Input not valid";
                            } else {
                            text = "Input OK";
                            }
                            document.getElementById("demo").innerHTML = text;
                        }
                    </script>
                

HTML form validation can be performed automatically by the browser.

Examples

If a form field (fname) is empty, the "required" attribute prevents this form from being submitted.

If you click submit, without filling out the text field, your browser will display an error message.

code:
                    <form  class=spec action="/action_page.html" method="post">
                        <input type="text" name="fname" required>
                        <input type="submit" value="Submit">
                    </form>
                

data validation

This is the process of ensuring that user input is clean, correct, and useful. Validation can be defined by many different methods, and deployed in many different ways.

"Server side validation" is performed by a web server, after input has been sent to the server.
"Client side validation" is performed by a web browser, before input is sent to a web server.

constraint validation

HTML5 introduced a new HTML validation concept called "constraint validation". HTML constraint validation is based on:

1/ "Constraint validation" HTML input attributes

disabled - specifies that the input element should be disabled.

max - specifies the maximum value of an input element.

min - specifies the minimum value of an input element.

pattern - specifies the value pattern of an input element.

required - specifies that the input field requires an element.

type - specifies the type of an input element.

2/ "Constraint validation" CSS pseudo selectors

:disabled - selects input elements with the "disabled" attribute specified.

:invalid - selects input elements with invalid values.

:optional - selects input elements with no "required" attribute specified.

:required - selects input elements with the "required" attribute specified.

:valid - selects input elements with valid values.

3/ "Constraint validation" DOM properties and methods

checkValidity() - returns true if an input element contains valid data.

setCustomValidity() - sets the validationMessage of an input element.

validity - contains boolean properties related to the validity of an input element.

validationMessage - contains the message a browser will display when the validity is false.

willValidate - indicates if an input element will be validated.


JavaScript validation API

top

constraint validation DOM methods

checkValidity() - returns true if an input element contains valid data.

setCustomValidity() - sets the validationMessage property of an input element.

Examples

Enter a number and click OK:

If the number is less than 100 or greater than 300, an error message will be displayed.

code:
                    <div class="spec">
                        <p>Enter a number and click OK:</p>
                        <input id="id1" type="number" min="100" max="300" required>
                        <button onclick="myFunc()">OK</button>
                        <p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>
                        <p id="dem1"></p>        
                    </div>
                    <script>
                        function myFunc() {
                            var inpObj = document.getElementById("id1");
                            if (!inpObj.checkValidity()) {
                                document.getElementById("dem1").innerHTML = inpObj.validationMessage;
                            } else {
                                document.getElementById("dem1").innerHTML = "Input OK";
                            } 
                        } 
                    </script> 
                

constraint validation DOM properties

validity - contains boolean properties related to the validity of an input element.

validationMessage - contains the message a browser will display when the validity is false.

willValidate - indicates if an input element will be validated.

validity properties

The validity property of an input element contains a number of properties related to the validity of data:

customError - set to true, if a custom validity message is set.

patternMismatch - set to true, if an element's value does not match its pattern attribute.

rangeOverflow - set to true, if an element's value is greater than its max attribute.

rangeUnderflow - set to true, if an element's value is less than its min attribute.

stepMismatch - set to true, if an element's value is invalid per its step attribute.

tooLong - set to true, if an element's value exceeds its maxLength attribute.

typeMismatch - set to true, if an element's value is invalid per its type attribute.

valueMissing - set to true, if an element (with a required attribute) has no value.

valid - set to true, if an element's value is valid.


Forms examples

top

Some examples

examples
Name:
code:
                    <div class="spec">
                        <form name="myForm1" action="/action_page.php" onsubmit="return validateForm()" method="post">
                            Name: <input type="text" name="fname1">
                            <input type="submit" value="Submit">
                        </form>         
                    </div>
                    <script>
                        function validateForm() {
                        var x = document.forms["myForm1"]["fname1"].value;
                        if (x == "") {
                            alert("Name must be filled out");
                            return false;
                        }
                        }
                    </script>
                

Fahrenheit to Celsius converter

Enter a temperature in degrees F:

Click this button to calculate the temperature in degrees C:

Temperature in degrees C is:

code:
                    <div class="spec">
                        <form>
                            <p> Enter a temperature in degrees F: <input name="degF" value=" " 
                            maxlength="15" size=15></p>
                            <p>Click this button to calculate the temperature in degrees C:
                            <input name="calc" value="Calculate" type="button" onClick=temp(this.form)><p>
                            <p>Temperature in degrees C is: <input name="degC" readonly size=15></p>
                        </form>    
                    </div>
                    <script>
                        function temp(form) {
                            var f = parseFloat(form.degF.value, 10);
                            var c = 0;
                            c = (f - 32.0) * 5.0 / 9.0;
                            form.degC.value = c;
                        }
                    
                    </script>
                

JavaScript.info - examples

examples
navigation: form and elements:
                    <form name="my">
                        <input name="one" value="1">
                        <input name="two" value="2">
                    </form>
                    <script>
                        // get the form
                        let form = document.forms.my; // <form name="my"> element
                        // get the element
                        let elem = form.elements.one; // <input name="one"> element
                        alert(elem.value); // 1
                    </script>

                    <form>
                        <input type="radio" name="age" value="10">
                        <input type="radio" name="age" value="20">
                    </form>
                    <script>
                        let form = document.forms[0];
                        let ageElems = form.elements.age;
                        alert(ageElems[0]); // [object HTMLInputElement]
                    </script>
                
backreference: element.form:
                    <form id="form">
                        <input type="text" name="login">
                    </form>
                    <script>
                        // form -> element
                        let login = form.login;
                        // element -> form
                        alert(login.form); // HTMLFormElement
                    </script>