简体   繁体   中英

How can i validate form with JavaScript

I want to create a form and want to validate user input, if user fill both text box i want to show an alert box, also if user fill one and left empty another one i want to show an alert box to let them know that they are missing one box. How i can do it with JavaScript, please help.

I want two text box, if user fill both text box and click enter i want to show an alert box telling them "Correct", if user fill one and left another empty i want to show an alert box telling them that it is "Incorrect". How i can do it, help.

 <form action="" method="post">
  <input type="text" name="text1" placeholder="Text 1">
</br>
  <input type="text" name="text2" placeholder="Text 2">
</br>
  <input type="submit" value="Enter">
</form>

What kind of validation are you interested in ? You can do everything with javascript my friend:).

This is pure javascript. To make it simple, I kept the html and js in one file. I also added a name to a form as you see below, in case you would have multiple forms.

<html>
    <body>

    <form name="LovelyForm" action="" method="post"> 
      <input type="text" name="text1" placeholder="Text 1"> </br> 
      <input type="text" name="text2" placeholder="Text 2"> </br> 
      <input type="submit" onclick="validateForm()" value="Enter">
    </form>

    <script type="text/javascript">
        function validateForm() {

            var x = document.forms["LovelyForm"]["text1"].value;
            var y = document.forms["LovelyForm"]["text2"].value;
            if (x == null || x == "" || y == null || y == "") {
                alert("Fill me in");
                return false;
            }else{
                alert("Good");
                return true;
            }
        }

    </script>
    </body>
</html>

Here's a JSFiddle that should work with IE < 9: http://jsfiddle.net/ayr7yov7/1/

form.elements['one'].value may cause issues if the inputs are not of type text .

The code:

<script>
    function trim(str) {
      if(!str) return '';

      return str.replace(/\s{2,}/g, '');
    }

    function valid(form) {
        var v1 = trim(form.elements['one'].value),
            v2 = trim(form.elements['two'].value);

        if (v1 === '') {
            alert('one');
            return false;
        }

        if (v2 === '') {
            alert('two');
            return false;
        }

        alert('full!')
        return true;
    }

</script>
<form action="/echo/json/" onsubmit="return valid(this)">
    <input name="one" type="text" />
    <input name="two" type="text" />
    <input type="submit" />
</form>

Validation with javascript is the most flexible way and works with all browsers, if you learn JQuery you will be able to improve the user experience limit less.

If you don't want to javascript then use the new improved input validation options with Html 5, they will work with most browsers and not break the ones without Html5 support.

Here: Best practice as I see it :)

  • Only validate the most necessary on client side.
  • Avoid compulsory input unless they realy are.
  • Don't refuse space, hyphens, commas, dots and so on if you absolutely don't have to. People like to cut and paste. You can always clean on server side.
  • Don't limit input length/size if you don't have to. Again people like to cut and paste and many times the input is to long just because it contains blank spaces.
  • Most important of all. You must always validate on server side, to make sure your data won't get corrupted. Client validation is only to improve the users experience and not a substitute.

First step is to give JavaScript an easy way to reference the element in the DOM . Generally, the easiest way is to give each element you need to reference a unique ID.

<input id="num1" />
<input id="num2" />

Then, JavaScript can access the inputs with the getElementById() method of the document object (the "D" from DOM).

var i1 = document.getElementById("num1");
var i2 = document.getElementById("num1");

Now, i1 and i2 contain a reference to their respective input objects (the "O" from DOM). Every form element object has a value attribute that contains the current value of it's input.

var val1 = i1.value;
var val2 = i2.value;

Now var1 and var2 contain the value of the input. All you have to do is check and see if they both have a value that isn't empty.

if(
    // if the first value does not equal an empty string ""..
    val1 != ""
    // and the second value does not equal an empty string ""..
    && val1 != ""
)
// then alert 'correct'
alert("correct");
// or else, alert 'incorrect'
else alert('incorrect');

Now you can throw it in a function and make it run when the form is submitted by attaching it to an event handler . When you're just starting it's easiest to use an onsubmit attribute, which takes the name of a function and calls that function when the form is submitted.

<form action="#" onsubmit="validate()">
    <input id="num1" />
    <input id="num2" />
    <input type="submit" />
</form>

<script>
    function validate(){
        var i1 = document.getElementById("num1");
        var i2 = document.getElementById("num1");
        var val1 = i1.value;
        var val2 = i2.value;
        if(val1 != "" && val2 != "") alert("correct");
        else alert("incorrect");
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM