How do I validate URL, but ignore if http:// or blank?

China☆狼群 提交于 2020-01-04 05:45:12

问题


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?

Thanks


回答1:


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

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

hope that helps

EDIT

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

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

allowEmpty-> a field may be blank


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

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;
    }
    ..
}



来源:https://stackoverflow.com/questions/4783872/how-do-i-validate-url-but-ignore-if-http-or-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!