Form Validation using JavaScript

后端 未结 5 1221
-上瘾入骨i
-上瘾入骨i 2021-01-25 02:44

I\'m trying to validate a form using JavaScript but i\'m a bit stuck on displaying a message next to the field to say that \"This field is required\". How do I go about doing th

相关标签:
5条回答
  • 2021-01-25 03:21

    Your way of validation form fields is absolutely terrible, a lot of unneded and bloated code which is not optimized at all.

    I will strongly reccomend you use some sort of readyly available FormValidation script or have a look at this jQuery plugin
    Using jQuery your code can look like this (plus you also get the messages to appear next to field):

    $("#signupForm").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            username: {
                required: true,
                minlength: 2
            },
            password: {
                required: true,
                minlength: 5
            },
            confirm_password: {
                required: true,
                minlength: 5,
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true
            }
        }
    })
    
    0 讨论(0)
  • 2021-01-25 03:28

    I think you need to take a look at this http://www.w3schools.com/js/js_form_validation.asp for the validation thing then take the ideas you have here to display your message.

    0 讨论(0)
  • 2021-01-25 03:30

    Add a span near each field so you can use it for the validation message:

    <td>First Name</td>
    <td>
      <input id="firstname" type="text" name="firstName" maxlength="30" />
      <span id="firstname_error"/>
    </td>
    

    After that, just add the error message there, so instead of:

    alert('You need to complete this field')
    

    You would use:

    document.getElementById('firstname_error').innerHTML = 'You need to complete this field'
    
    0 讨论(0)
  • 2021-01-25 03:30

    I looked at the jQuery code. Looks like thousands of lines of code for some relatively simple validation. I would not recommend using the plugin for some simple validation - it is overkill.

    0 讨论(0)
  • 2021-01-25 03:32

    Simplest way is to put a hidden span tag below the input field like so

    <input .... /> <br />
    <span id="fieldname" style="display: none;">This field is required</span>
    

    In Javascript you can do this

    if(!valid)
    {
      document.getElementById("fieldname").style = "block";
    }
    
    0 讨论(0)
提交回复
热议问题