Registration form validation

后端 未结 2 552
甜味超标
甜味超标 2021-01-27 08:18

I want to validate this form ignoring default values of input fields. I tried all possible ways with jQuery validate plugin. It\'s hard to understand how to use it, since I\'m a

2条回答
  •  星月不相逢
    2021-01-27 08:55

    First I think you should add an id to each form element. I don't think jQuery will grab a DOM element with its name. Your form has an id but not your input elements.

    So for example, see the input element below (the id can be same as the name):

    
    

    Now you can grab that element via jQuery like this: alert($('#pwd').val());

    The # before pwd indicates that the element is being selected by its id. You could also select an element by referecing its class like this: alert($('.className').val()); but this will select all matching elements with the same class applied to them. To make a single and specific select; you should use ids.

    So, if I understand your question right; you can validate the value of these elements by checking whether they have the default value or if they are empty first. Then checking other criterias such as password length, etc..

        $('#reg').submit(function (event) 
        {
            if ($('#pwd').val() == defaultValues['pwd'] || $.trim($('#pwd').val()) == '')
            {
                alert('Please enter a password!');
                return false;
            }
            else
            {
                if ($('#pwd').val().length < 8)
                {
                    alert('Password must have 8 characters at least!');
                    return false;
                }
            }
        });
    

    Note: I agree with Jared. You should validate this form on the server-side too; since the code is visible in the browser and can easily be by-passed.

提交回复
热议问题