登记表验证

发布于 2024-11-29 13:00:36 字数 2715 浏览 0 评论 0原文

我想验证此表单,忽略输入字段的默认值。我使用 jQuery 验证插件尝试了所有可能的方法。由于我是 JS 的初学者,所以很难理解如何使用它。

我的表单看起来像这样

<?php
require "core/code/includes/db.php";
if (mysqli_connect_errno()) {
        printf("Baza ilə əlaqədə problem var: %s\n Xahiş edirik administrator ilə əlaqə yaradasınız: [email protected]", mysqli_connect_error());
        exit();
    }
?>
<form id="reg" method="post" action="core/code/functions/signup.php" onSubmit="return checkForm(this);">
<table width="270px" style="clear:both">
<tr>
<td class="numbers" rowspan="3">
1
</td>
<td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
Əsas məlumatlar 
</td>
</tr>
<tr>
 <td ><input class="part1 default required" type="text" name="fname" value="Adınız"  /></td>
  <td ><input  class="part1 default required"  type="text" name="mname"  value="Atanızın adı"/></td>
 <td ><input  class="part1 default" type="text" name="lname"  value="Soyadınız" /></td>
</tr>
...

...
<input class="button button-gray"  type="submit" value="Tamam" name="submit"/>
</p>
</form>
<script type="text/javascript" src="core/code/js/jquery-ui.js"></script>
<script src="core/code/js/mask.js"></script>
<script src="core/code/js/reg.js"></script>
<script type="text/javascript" src="core/code/js/acompl.js"></script>  

和 reg.js

var defaultValues = {
    'fname': 'Adınız',
    'mname': 'Atanızın adı',
    'lname': 'Soyadınız',
    'phone': 'Telefon',
    'email': 'Email',
    'pwd':'Şifrə',
    'region':'Rayon',
    'school':'Məktəb',
    'login':'Istifadəçi adı',
    'class':'Sinif',
    'subject':'Fənnin adını daxil edin',
    'dob': 'Date of Birth'
};
$('input').live('focus', function() {
    var el = $(this);
    if (el.hasClass('default')) {
        el.removeClass('default').val('');
    }
    if (el.attr('id') === 'dob') {
        $(this).mask('99.99.9999', {placeholder:' '});
    }
});

$('input').live('blur', function() {
    var el = $(this);
    var name = el.attr('name');

    // Really we only want to do anything if the field is *empty*
    if (el.val().match(/^[\s\.]*$/)) {

        // To get our default style back, we'll re-add the classname
        el.addClass('default');

        // Unmask the 'dob' field
        if (name == 'dob') {
            el.unmask();
        }

        // And finally repopulate the field with its default value
        el.val(defaultValues[name]);
    }
});

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 beginner to JS.

My form looks like that

<?php
require "core/code/includes/db.php";
if (mysqli_connect_errno()) {
        printf("Baza ilə əlaqədə problem var: %s\n Xahiş edirik administrator ilə əlaqə yaradasınız: [email protected]", mysqli_connect_error());
        exit();
    }
?>
<form id="reg" method="post" action="core/code/functions/signup.php" onSubmit="return checkForm(this);">
<table width="270px" style="clear:both">
<tr>
<td class="numbers" rowspan="3">
1
</td>
<td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
Əsas məlumatlar 
</td>
</tr>
<tr>
 <td ><input class="part1 default required" type="text" name="fname" value="Adınız"  /></td>
  <td ><input  class="part1 default required"  type="text" name="mname"  value="Atanızın adı"/></td>
 <td ><input  class="part1 default" type="text" name="lname"  value="Soyadınız" /></td>
</tr>
...

...
<input class="button button-gray"  type="submit" value="Tamam" name="submit"/>
</p>
</form>
<script type="text/javascript" src="core/code/js/jquery-ui.js"></script>
<script src="core/code/js/mask.js"></script>
<script src="core/code/js/reg.js"></script>
<script type="text/javascript" src="core/code/js/acompl.js"></script>  

And reg.js

var defaultValues = {
    'fname': 'Adınız',
    'mname': 'Atanızın adı',
    'lname': 'Soyadınız',
    'phone': 'Telefon',
    'email': 'Email',
    'pwd':'Şifrə',
    'region':'Rayon',
    'school':'Məktəb',
    'login':'Istifadəçi adı',
    'class':'Sinif',
    'subject':'Fənnin adını daxil edin',
    'dob': 'Date of Birth'
};
$('input').live('focus', function() {
    var el = $(this);
    if (el.hasClass('default')) {
        el.removeClass('default').val('');
    }
    if (el.attr('id') === 'dob') {
        $(this).mask('99.99.9999', {placeholder:' '});
    }
});

$('input').live('blur', function() {
    var el = $(this);
    var name = el.attr('name');

    // Really we only want to do anything if the field is *empty*
    if (el.val().match(/^[\s\.]*$/)) {

        // To get our default style back, we'll re-add the classname
        el.addClass('default');

        // Unmask the 'dob' field
        if (name == 'dob') {
            el.unmask();
        }

        // And finally repopulate the field with its default value
        el.val(defaultValues[name]);
    }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青衫负雪 2024-12-06 13:00:37

首先,我认为您应该为每个表单元素添加一个 id 。我不认为 jQuery 会获取 DOM 元素及其 name。您的表单有一个 id,但没有您的输入元素。

例如,请参阅下面的输入元素(id 可以与名称相同):

<input class="part1 default required" type="text" name="pwd" id="pwd" value="Adınız"  />

现在您可以通过 jQuery 获取该元素,如下所示: alert($('#pwd').val());< /code>

pwd 之前的 # 表示该元素是通过其 id 选择的。
您还可以通过引用其类来选择元素,如下所示: alert($('.className').val()); 但这将选择应用了相同类的所有匹配元素。进行单一且具体的选择;你应该使用id。

所以,如果我理解你的问题的话;您可以通过检查这些元素是否具有默认值或者它们是否为空来验证这些元素的值。然后检查其他标准,例如密码长度等。

    $('#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;
            }
        }
    });

注意:我同意 Jared 的观点。您也应该在服务器端验证此表单;因为代码在浏览器中可见并且很容易被绕过。

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):

<input class="part1 default required" type="text" name="pwd" id="pwd" value="Adınız"  />

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.

何必那么矫情 2024-12-06 13:00:37

这在某种程度上可能有点过头了,但我想在这里展示一些不同的东西。主要是:

  • 命名空间事件处理程序
  • 自定义事件处理
  • 触发事件处理程序
  • 错误检测和处理错误数组
  • 使用属性和 $.data() 来存储与元素相关的数据
  • 使用结构化对象来配置表单

阅读评论,如果您有任何疑问,请告诉我。

模拟 HTML

<form id="reg" method="post" action="core/code/functions/signup.php">
<table width="270px" style="clear:both">
<tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">Əsas məlumatlar</td>
</tr>
<tr>
 <td><input class="part1 default required" type="text" name="fname" value=""/></td>
 <td><input class="part1 default required" type="text" name="mname" value=""/></td>
 <td><input class="part1 default" type="text" name="lname" value=""/></td>
</tr>
<tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
     Password: <input class="part1 default required" type="text" name="pwd"/>
 </td>
<tr>
</tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
     DOB: <input class="part1 default required" type="text" name="dob"/>
 </td>
</tr>
<tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
     Phone: <input class="part1 default" type="text" name="phone"/>
 </td>
</tr>
</table>
<p><input class="button button-gray"  type="submit" value="Tamam" name="submit"/></p>
</form>

Javascript

// An object containing different fields by name and
// objects that provide information about the object the
// name points to. 'default' property is required.
var defaultValues = {
    'fname': {'default':'Adınız'},
    'mname': {'default':'Atanızın adı'},
    'lname': {'default':'Soyadınız'},
    'phone': {'default':'Telefon'},
    'email': {'default':'Email'},
    'pwd': {
        'default':'Şifrə',
        // Text used to display a custom error text.
        // Otherwise, the default text will be used.
        'errortext':'Password must be 5 characters or more in length',
        // A custom function to be called when the element is validated
        // and/or checked for default. This is added as a custom event
        // handler called 'validation' and called on blur.checkRequired
        // and from the function checkRequired() when the
        // blur.checkRequired is triggered. The 'notvalidated' data
        // element is how the validation failure is passed back to
        // blur.checkDefault event.
        'onvalidation': function(){
            if (this.value.length < 5) {
                $(this).data('notvalidated',true);
            } else {
                $(this).data('notvalidated',false);
            }
        }
    },
    'region': {'default':'Rayon'},
    'school': {'default':'Məktəb'},
    'login': {'default':'Istifadəçi adı'},
    'class': {'default':'Sinif'},
    'subject': {'default':'Fənnin adını daxil edin'},
    'dob': {
        'default':'Date of Birth',
        // An alternate value to check for, in addition to
        // the default. More complex checks should be checked
        // through the onvalidation handler.
        'validate':'  .  .    ',
        'errortext':'A correct Date of Birth must be entered.'
    }
};
function checkRequired() {
    // We will attach the error list to the body tag.
    var $body = $('body');
    // This array will store the actual errors, but this specfically
    // clears previous errors caught.
    $body.data('requiredErrors',[]);
    $('input.required').each(function(){
        // Trigger is used to manually call the blur.checkRequired
        // handler.
        $(this).trigger('blur.checkRequired');
    });
    // Get a reference to the errors generated by the triggered
    // event handler.
    var errors = $body.data('requiredErrors');
    if (errors.length > 0) {
        // This will allow you output an error to the user.
        var errortext = "There were "+errors.length+" errors "+
            "submitting the form.<br/>"+
            "These errors must be fixed before submitting the form."+
            "<ul>";
        for (var i = 0; i < errors.length; i++) {
            errortext += "<li>"+errors[i]+"</li>";
        }
        errortext += '</ul>';
        errortext = '<div id="requiredErrorsText">'+errortext+'</div>';
        // First try to remove it if it's already showing.
        $('#requiredErrorsText').remove();
        // At it to the top of the form.
        $(errortext).prependTo('form');
        // Return false to the submit event handler to prevent the form
        // from submitting.
        return false;
    }
    // Return true to allow the form to continue submitting.
    return true;
}
$(document).ready(function(){
    // Set the initial errors log array.
    $('body').data('requiredErrors',[]);
    // Loop through and apply the defaultValues object information
    // to the related elements.
    for (var name in defaultValues) {
        // Name is the key object reference and should point to an
        // input element with the name attribute equal to it.
        var $this = $('input[name="'+name+'"]');
        var validate = '';
        var errortext = '';
        // Only do the apply if their are elements found.
        if ($this.length != 0) {
            // Add the custom or default value to validate against.
            // If both are available, it will check both during the
            // blur.checkRequired handler.
            if (defaultValues[name].hasOwnProperty('validate')) {
                validate = defaultValues[name].validate;
            } else {
                validate = defaultValues[name].default;
            }
            // Set the value for the error text to display, defaulting
            // to the 'default' value if the property does not exist.
            if (defaultValues[name].hasOwnProperty('errortext')) {
                errortext = defaultValues[name].errortext;
            } else {
                errortext = defaultValues[name].default;
            }
            // Add the validation event handler, if present.
            if (typeof defaultValues[name].onvalidation == 'function') {
                $this.bind('validation',defaultValues[name].onvalidation);
                // Tell the blur.checkRequired() to run the validator handler.
                $this.data('usevalidator',true);
            } else {
                $this.data('usevalidator',false);
            }
            // Set the default value to the... default value if it is present
            // and the element's value is empty. Note, this will allow you to
            // not overwrite values returned by a roundtrip to the server
            // (in case the submit handler does not prevent the form being
            // being submitted.
            if ($this.val() == '' && defaultValues[name].default) {
                $this.val(defaultValues[name].default);
            }
            // Set custom attributes for the related values.
            $this.attr('default',defaultValues[name].default);
            $this.attr('validate',validate);
            $this.attr('errortext',errortext);
        }
    }
    $('form').submit(function(){
        // NOTE!!! I am return false to prevent the form in jsfiddle
        // from submitting the form EVER. This is just for diagnostic
        // reasons, it should not done in your production script.
        if (checkRequired()) {
            alert('Form will submit.');
        } else {
            alert('Form will NOT submit');
            return false;
        }
        // Remove this when you want to use this for real.
        return false;
    });
    // We will use a cached jQuery object.
    $default = $('input[type="text"][default],input[type="text"].required');
    // See http://api.jquery.com/bind/ for more on custom events,
    // including namespaced events like blur.checkRequired.
    $default.live('blur.checkRequired',function(){
        var $this = $(this);
        var $body = $('body');
        var notvalidated = true;
        // Having the 'required' class on the input causes it to
        // check for validation.
        if ($this.hasClass('required')) {
            // Triggers the custom validation handler.
            if ($this.data('usevalidator') === true) {
                $this.trigger('validation');
            }
            notvalidated = $this.val() == '' ||
                           $this.val() == $this.attr('default') ||
                           $this.val() == $this.attr('validate') ||
                           $this.data('notvalidated') === true;
            if (notvalidated) {
                $body.data('requiredErrors').push($this.attr('errortext'));
                $this.addClass('requiredError');
            } else {
                $this.removeClass('requiredError');
            }
        }
    });
    // Namespaced handlers prepended with a regular handler like
    // blur, focus, etc... will be fired with the regular handler.
    $default.live('focus.checkDefault', function() {
        var el = $(this);
        if (el.hasClass('default')) {
            el.removeClass('default').val('');
        }
        if (el.attr('name') === 'dob') {
            $(this).mask('99.99.9999', {placeholder:' '});
        }
    });
    $default.live('blur.checkDefault', function() {
        var el = $(this);
        var name = el.attr('name');

        // Really we only want to do anything if the field is *empty*
        if (el.val().match(/^[\s\.]*$/)) {

            // To get our default style back, we'll re-add the classname
            el.addClass('default');

            // Unmask the 'dob' field
            if (name == 'dob') {
                el.unmask();
            }

            // And finally repopulate the field with its default value
            el.val(el.attr('default'));
        }
    });
});

http://jsfiddle.net/userdude /CMmDF/

This might be overkill in a way, but I wanted to demonstrate a few different things here. Primarily:

  • Namespacing event handlers
  • Custom event handling
  • Triggering event handlers
  • Error detection and handling with an array of errors
  • Using attributes and $.data() to store your element-related data
  • Using a structured object to configure your form

Read through the comments and let me know if you have any questions.

Mock HTML

<form id="reg" method="post" action="core/code/functions/signup.php">
<table width="270px" style="clear:both">
<tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">Əsas məlumatlar</td>
</tr>
<tr>
 <td><input class="part1 default required" type="text" name="fname" value=""/></td>
 <td><input class="part1 default required" type="text" name="mname" value=""/></td>
 <td><input class="part1 default" type="text" name="lname" value=""/></td>
</tr>
<tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
     Password: <input class="part1 default required" type="text" name="pwd"/>
 </td>
<tr>
</tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
     DOB: <input class="part1 default required" type="text" name="dob"/>
 </td>
</tr>
<tr>
 <td colspan="3" style="font-weight:bold; color:#333; font-size:13px">
     Phone: <input class="part1 default" type="text" name="phone"/>
 </td>
</tr>
</table>
<p><input class="button button-gray"  type="submit" value="Tamam" name="submit"/></p>
</form>

Javascript

// An object containing different fields by name and
// objects that provide information about the object the
// name points to. 'default' property is required.
var defaultValues = {
    'fname': {'default':'Adınız'},
    'mname': {'default':'Atanızın adı'},
    'lname': {'default':'Soyadınız'},
    'phone': {'default':'Telefon'},
    'email': {'default':'Email'},
    'pwd': {
        'default':'Şifrə',
        // Text used to display a custom error text.
        // Otherwise, the default text will be used.
        'errortext':'Password must be 5 characters or more in length',
        // A custom function to be called when the element is validated
        // and/or checked for default. This is added as a custom event
        // handler called 'validation' and called on blur.checkRequired
        // and from the function checkRequired() when the
        // blur.checkRequired is triggered. The 'notvalidated' data
        // element is how the validation failure is passed back to
        // blur.checkDefault event.
        'onvalidation': function(){
            if (this.value.length < 5) {
                $(this).data('notvalidated',true);
            } else {
                $(this).data('notvalidated',false);
            }
        }
    },
    'region': {'default':'Rayon'},
    'school': {'default':'Məktəb'},
    'login': {'default':'Istifadəçi adı'},
    'class': {'default':'Sinif'},
    'subject': {'default':'Fənnin adını daxil edin'},
    'dob': {
        'default':'Date of Birth',
        // An alternate value to check for, in addition to
        // the default. More complex checks should be checked
        // through the onvalidation handler.
        'validate':'  .  .    ',
        'errortext':'A correct Date of Birth must be entered.'
    }
};
function checkRequired() {
    // We will attach the error list to the body tag.
    var $body = $('body');
    // This array will store the actual errors, but this specfically
    // clears previous errors caught.
    $body.data('requiredErrors',[]);
    $('input.required').each(function(){
        // Trigger is used to manually call the blur.checkRequired
        // handler.
        $(this).trigger('blur.checkRequired');
    });
    // Get a reference to the errors generated by the triggered
    // event handler.
    var errors = $body.data('requiredErrors');
    if (errors.length > 0) {
        // This will allow you output an error to the user.
        var errortext = "There were "+errors.length+" errors "+
            "submitting the form.<br/>"+
            "These errors must be fixed before submitting the form."+
            "<ul>";
        for (var i = 0; i < errors.length; i++) {
            errortext += "<li>"+errors[i]+"</li>";
        }
        errortext += '</ul>';
        errortext = '<div id="requiredErrorsText">'+errortext+'</div>';
        // First try to remove it if it's already showing.
        $('#requiredErrorsText').remove();
        // At it to the top of the form.
        $(errortext).prependTo('form');
        // Return false to the submit event handler to prevent the form
        // from submitting.
        return false;
    }
    // Return true to allow the form to continue submitting.
    return true;
}
$(document).ready(function(){
    // Set the initial errors log array.
    $('body').data('requiredErrors',[]);
    // Loop through and apply the defaultValues object information
    // to the related elements.
    for (var name in defaultValues) {
        // Name is the key object reference and should point to an
        // input element with the name attribute equal to it.
        var $this = $('input[name="'+name+'"]');
        var validate = '';
        var errortext = '';
        // Only do the apply if their are elements found.
        if ($this.length != 0) {
            // Add the custom or default value to validate against.
            // If both are available, it will check both during the
            // blur.checkRequired handler.
            if (defaultValues[name].hasOwnProperty('validate')) {
                validate = defaultValues[name].validate;
            } else {
                validate = defaultValues[name].default;
            }
            // Set the value for the error text to display, defaulting
            // to the 'default' value if the property does not exist.
            if (defaultValues[name].hasOwnProperty('errortext')) {
                errortext = defaultValues[name].errortext;
            } else {
                errortext = defaultValues[name].default;
            }
            // Add the validation event handler, if present.
            if (typeof defaultValues[name].onvalidation == 'function') {
                $this.bind('validation',defaultValues[name].onvalidation);
                // Tell the blur.checkRequired() to run the validator handler.
                $this.data('usevalidator',true);
            } else {
                $this.data('usevalidator',false);
            }
            // Set the default value to the... default value if it is present
            // and the element's value is empty. Note, this will allow you to
            // not overwrite values returned by a roundtrip to the server
            // (in case the submit handler does not prevent the form being
            // being submitted.
            if ($this.val() == '' && defaultValues[name].default) {
                $this.val(defaultValues[name].default);
            }
            // Set custom attributes for the related values.
            $this.attr('default',defaultValues[name].default);
            $this.attr('validate',validate);
            $this.attr('errortext',errortext);
        }
    }
    $('form').submit(function(){
        // NOTE!!! I am return false to prevent the form in jsfiddle
        // from submitting the form EVER. This is just for diagnostic
        // reasons, it should not done in your production script.
        if (checkRequired()) {
            alert('Form will submit.');
        } else {
            alert('Form will NOT submit');
            return false;
        }
        // Remove this when you want to use this for real.
        return false;
    });
    // We will use a cached jQuery object.
    $default = $('input[type="text"][default],input[type="text"].required');
    // See http://api.jquery.com/bind/ for more on custom events,
    // including namespaced events like blur.checkRequired.
    $default.live('blur.checkRequired',function(){
        var $this = $(this);
        var $body = $('body');
        var notvalidated = true;
        // Having the 'required' class on the input causes it to
        // check for validation.
        if ($this.hasClass('required')) {
            // Triggers the custom validation handler.
            if ($this.data('usevalidator') === true) {
                $this.trigger('validation');
            }
            notvalidated = $this.val() == '' ||
                           $this.val() == $this.attr('default') ||
                           $this.val() == $this.attr('validate') ||
                           $this.data('notvalidated') === true;
            if (notvalidated) {
                $body.data('requiredErrors').push($this.attr('errortext'));
                $this.addClass('requiredError');
            } else {
                $this.removeClass('requiredError');
            }
        }
    });
    // Namespaced handlers prepended with a regular handler like
    // blur, focus, etc... will be fired with the regular handler.
    $default.live('focus.checkDefault', function() {
        var el = $(this);
        if (el.hasClass('default')) {
            el.removeClass('default').val('');
        }
        if (el.attr('name') === 'dob') {
            $(this).mask('99.99.9999', {placeholder:' '});
        }
    });
    $default.live('blur.checkDefault', function() {
        var el = $(this);
        var name = el.attr('name');

        // Really we only want to do anything if the field is *empty*
        if (el.val().match(/^[\s\.]*$/)) {

            // To get our default style back, we'll re-add the classname
            el.addClass('default');

            // Unmask the 'dob' field
            if (name == 'dob') {
                el.unmask();
            }

            // And finally repopulate the field with its default value
            el.val(el.attr('default'));
        }
    });
});

http://jsfiddle.net/userdude/CMmDF/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文