Zend Framework 2 - Annotation form, RegEx validation and custom error messages

旧时模样 提交于 2019-12-12 10:12:18

问题


As outlined here I'm working with GeoPositionFields. Because this is not supported from Zend, I went with a standard RegEx validator.

It works great but I still need a custom error message - any ideas how to achieve this?

The one in my example just does nothing...

/**
 * @ORM\Column(type="string")
 * @Form\Filter({"name":"StringTrim"})
 * @Form\Validator({"name":"Regex", "options":{"pattern":"/(-?\d{1,3}\D\d+)[^\d-]+(-?\d{1,3}\D\d+)/"}})
 * @Form\ErrorMessage("My custom message")
 * @Form\Attributes({"type":"text"})
 * @Form\Options({"label":"GeoPos"})
 *
 */
protected $geopoint;

Even this one is just beeing ignored:

@Form\Messages({"regexNotMatch": "My custom message"})

回答1:


You will have to overwrite the default messages using the messages key from the options.

Try this (i guess you'll have to trim this into one line though for the annotations to work ;) That's up to you, hehe.

@Form\Validator({
    "name":"regex", 
    "options":{
        "pattern":"/(-?\d{1,3}\D\d+)[^\d-]+(-?\d{1,3}\D\d+)/",
        "messages":{
            "regexInvalid":"Regex is invalid, Booo!",
            "regexNotMatch": "Input doesn't match, bleeeeh!",
            "regexErrorous": "Internal error, i'm like wtf!"
        }
    }
})

Each Validator has it's own messages. You're best advised to see the Source-Code to find out what ErrorMessages are present within each Element. To give you an example, please follow this link (click) to see how to find out about the messages-keys.

When using the array-style-syntax for creating forms outside of Annotations, it may be a little bit safer to go the statis approach for the keys like

'messages' => array(
    \Zend\Validator\Regex::INVALID => "Regex is invalid, Booo!",
    //etc...
)

Since strings - at least in theory - could always change, the constants won't.




回答2:


/^(\-?\d+(?:\.\d+)?),?\s*(\-?\d+(?:\.\d+)?)$/

This regexp validates and captures GEO input:

  • In format Latitude, Longitude
  • In format Latitude Longitude
  • Coordinates copied directly from GoogleMaps


来源:https://stackoverflow.com/questions/14068446/zend-framework-2-annotation-form-regex-validation-and-custom-error-messages

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