Is there way to use custom validation on an advanced custom field? For example, I might not want a textfield to have a value that starts with certain prefix, or I might want a number field to have a value greater than ‘x’. I might also want to run a regex against a value and return an error if it doesn’t match.
Leave a Reply
You must be logged in to post a comment.
There is now, I just posted a plugin that I wrote to do validation for Advanced Custom Fields to the WordPress repository. It lets you do server side validation using either PHP code or regex, jQuery masked inputs, as well as unique value settings.
http://wordpress.org/extend/plugins/validated-field-for-acf/
I did it by plugging into
acf/pre_save_post
. Using that, you can test the $_POST data. And if you don’t like something, you can change $post_id to “error” when you return it. This will keep the form from processing since the post_id is not correct. You can also plug in toacf/save_post
to make sure to unset the “return” or update messages from the form.It is all a little complicated, but I will try to give a simplified example of what I used.
This doesn’t allow to highlight fields that returned an error, but you could actually do it pretty easily with javascript using the classes from the errors in
#message
div.Since version 5.0, you can use the
acf/validate_value
filter – see the official documentation.you can use this code
result
Documentation