jquery.validation-验证必填字段时如何忽略默认值 [英] jquery.validation - how to ignore default values when validating mandatory fields

查看:869
本文介绍了jquery.validation-验证必填字段时如何忽略默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery验证插件来验证注册表单.

I am using jquery validation plugin to validate a registration form.

每个文本输入字段在输入框中预先填充了说明作为值

Each text input field has instructions pre-filled as values in the input box

ex:对于文本输入框id =名称",默认值将设置为输入您的名称".我粘贴了以下示例代码:

ex: for a text-input box id='Name', the default value will be set to 'Enter Your Name'. I have pasted below sample code:

<input type="text" id="Name" value="Enter Your Name" onfocus="if(this.value == 'Your Name'){this.value = '';}" type="text" class="required" onblur="if(this.value == ''){this.value='Your Name';}" size="25" />

我需要知道的是如何在验证规则中进行指定,以便在输入框包含默认消息或空值的情况下,插件引发必填字段错误.

What I need to know is how to specify in the validation rule such that the plugin throws a required field error if the input box contains either the default message or empty values.

不胜感激.

推荐答案

我通过使用validateator.addMethod创建自定义验证来找出解决问题的方法,这确实很简单.

I figured a way around the problem by creating a custom validation using validator.addMethod, which is really easy.

我在下面粘贴了我的验证块的片段:

I have pasted a snippet of my validation block below:

   //1. Define custom validation 
    $(document).ready(function() 
    {
    jQuery.validator.addMethod("defaultInvalid", function(value, element) 
    {
     switch (element.value) 
     {
      case "Your Name": -- this will be the default value in the Name text box
       if (element.name == "Your Name")
          return false;
     }
    }
    //2. Include custom validation in the rules for your element
    $("#aspnetForm").validate(
    {
      rules: 
      {
       Name: "required defaultInvalid"
      },
      messages: 
      {
       Name: "Please input your name"
      }
    })
   }

我对所有具有默认值的元素都使用了相同的形式.这很好用.

I have used the same for all the elements which have default values in the form. This works great.

这篇关于jquery.validation-验证必填字段时如何忽略默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆