如何验证URL,但如果http://或空白,则忽略它? [英] How do I validate URL, but ignore if http:// or blank?

查看:266
本文介绍了如何验证URL,但如果http://或空白,则忽略它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证网址的表单字段。我已将字段的默认值设置为http://。当用户没有输入URL,并留下http://时,它表示无效的URL。不需要URL,因此如果只有http://,则不应显示错误消息。

I want to validate a form field for URL. I have set the default for the field to http://. When the user doesn't enter a URL, and leaves the http://, it says invalid URL. URL is not required, so if it's only http://, it should not show error message. How can I make it ignore if the person submits http:// as the URL?

感谢

推荐答案

http:// 不是有效的网址,因此如果您要允许它,则有2个选项

http:// is not a valid url, so if you want to allow it anyway there are 2 options


  1. 创建自定义验证规则 ,对于真实的网址+ http://

  2. 使用 before validate callback ,并将url字段设置为空白,如果只是 http://

  1. create a custom validation rule, that returns true for a real url + http://
  2. use the before validate callback and set the url field to blank if it is just http://

希望有助于

EDIT

我忘记了:你不需要设置required,但'allowEmpty'=>真实

I forgot: you don't need to set required but 'allowEmpty' => true

必须 - >表单必须包含发送到服务器的字段xyz

required -> the form must contain a field xyz that is send to the server

allowEmpty - >字段可能为空白

allowEmpty-> a field may be blank

我添加了链接到上面的回调函数,但无论如何,这里是:

I added the link to the callback function above, but anyway .. here it is:

在你的模型类(我只是假设它的 User ):

in your model class (I just suppose it's User):

class User extends AppModel {
    ..

    function beforeValidate() {
        if (isset($this->data['User']['url']) && $this->data['User']['url'] == 'http://') {
            $this->data['User']['url'] = '';
        }
        return true;
    }
    ..
}

这篇关于如何验证URL,但如果http://或空白,则忽略它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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