Insights

Custom Validation for Ninja Form – wordpress

Suppose you have used Ninja Form Plugin in your wordprss website.

Ninja form provide you the option to validate the fields like email address, phone numbers format and required validation.

But in case you have to add any custom validation then Ninja form provide you the hook to implement custom client side validation.

Link https://developer.ninjaforms.com/codex/client-side-field-validation/

So this example is to validation a field which require to have combination of alphabets and numbers, But not just numbers

  • Step 1Create a function to check if given value is numbers only
    function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }
    
  • Step 2Create a function to check if given values is alphanumeric
    function is_alphaNumeric(str)
    {
      regexp = /^[A-Za-z0-9\s,.-]+$/;
    
      if (regexp.test(str))
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    
  • Step 3Hook into ninja form function to trigger your custom validation before submit
        var myCustomFieldController = Marionette.Object.extend( {
        initialize: function() {
    
            // On the Form Submission's field validaiton...
            var submitChannel = Backbone.Radio.channel( 'submit' );
            this.listenTo( submitChannel, 'validate:field', this.validateRequired );
    
            // on the Field's model value change...
            var fieldsChannel = Backbone.Radio.channel( 'fields' );
            this.listenTo( fieldsChannel, 'change:modelValue', this.validateRequired );
        },
    
        validateRequired: function( model ) {
    
            //console.log(model.get( 'id' ))	
            if(model.get( 'id' ) == '48'){ // Here 48 is the id of the field which has to be validated
    			if( model.get( 'value' ) && !is_alphaNumeric(model.get( 'value' )) ) {
    				// Add Error to Model
     				Backbone.Radio.channel( 'fields' ).request( 'add:error', model.get( 'id' ), 'custom-field-error', 'Profession fields should contain alphabets and numbers only' );
    
    			}
    			else if( model.get( 'value' ) && isNumber(model.get( 'value' )) ) {
    				// Add Error to Model
     				Backbone.Radio.channel( 'fields' ).request( 'add:error', model.get( 'id' ), 'custom-field-error', 'Profession fields should contain alphabets and numbers and not just numbers' );
    
    			} 
    			else {
    				// Remove Error from Model
    				Backbone.Radio.channel( 'fields' ).request( 'remove:error', model.get( 'id' ), 'custom-field-error' );
    			}
    				
    		}
    
            // Check if Model has a value
        }
    });
    
    // On Document Ready...
    jQuery( document ).ready( function( $ ) {
    
        // Instantiate our custom field's controller, defined above.
        new myCustomFieldController();
    });
    

    This is all done. Now you can see the form throwing the error message that we have set in the custom field

Custom Validation for Ninja Form - wordpress
Custom Validation for Ninja Form – wordpress

You can also check the post on codepen

Turn insight into action

Need help with javascript or a related project?

If this article sparked an idea, question, or project direction, I can help you turn it into a practical next step.

Start a conversationChat on WhatsApp

Related reading

Articles connected to this topic

apache

401 Response when PHP-FPM Enabled on WordPress CMS

We recently migrated our website to another hosting service running FPM/FastCGI . We noticed under the website CMS -> tools -> Site Health Status , that all our REST API calls were failing authentication. It appeared to turn the request into an request from an Anonymous user even though we passed Basic Authentication h

Jan 2, 2025

Read article

css

How to find selected and unselected item in select2 dropdown

While using select2 library, if you have to find the selected and unselected item based on the change event when you check or uncheck the items. Based on the checked status, you may have to create some custom trigger or events then you can use the below code reference from codepen to achieve the save. […]

Dec 1, 2024

Read article

General

How to secure your website from attacks

1. Use HTTPS and SSL Certificates SSL (Secure Socket Layer): SSL encrypts the data transferred between the user’s browser and the server, preventing interception by attackers. Implementation: Obtain an SSL certificate from a trusted provider (many hosting companies offer free SSL). Force HTTPS in site settings and .hta

Nov 12, 2024

Read article

Most recent

Latest posts from the blog

View all articles →