How to add async custom validation using Telligent JavaScript Validation APIs

I am trying to add custom validation. Few validation options that I can use are listed here. However my validation is async in nature.

I am struggling to find a way to wait for async call to complete.

What I have tried so far is as below:

.evolutionValidation('addCustomValidation',
	'#txtCustomFieldName',
    function () {
        var fieldNameInput = $('#txtCustomFieldName');
        var fieldName = encodeURIComponent(fieldNameInput.val().trim());
        var result;
        // Async Call comes here
        WCF.Service.CheckIfValid(fieldName,
           function (resp) { //success
                 result = resp.IsValid;
           },
           function() { //failed
                 result = resp.IsValid
           }
        );
        
        // How to wait here till the result is resolved and available to return back
        // Like is JavaScript Promise or Defer supported or other way around?
return result; }, "Field is not valid please try again", fieldNameInput.closest('.field-item').find('.field-item-validation'), null);

Please help.

Cheers.

  • AFAIK, there's no way to make it wait at that point.

    Although you can do this: call an ajax method to calculate the result of your WCF.Service.CheckIfValid() method, store that in a javascript variable, and when the ajax method completes, call the validate method for submit button again, like:

    $('SELECTOR').evolutionValidation('validate')

    At this point your CustomValidation method can return the stored value. his will complete your validation.

    You can trigger the ajax method on value changed - of your 'fieldName' input field or something, but you will have to play around with scenarios like the ajax method getting called before you have entered all the field names, etc.

    Hope that helps.

  • In reply to Vinay Kalasannavar:

    I have solved this by adding additional validation type. Similar as we have 'passwordvalid', 'groupnameexists', etc

    Working validation code is shown below:

    Step 1: Extend the Telligent Validator definition with Our Own Field Validation

    (function (a) {
    	a.validator.addMethod("MyCustomFieldValidation", function (k, j, c) {
    		if (this.optional(j)) return "dependency-mismatch";
    		var MyFieldNameValue = encodeURIComponent(a.trim(k));
    		if (MyFieldNameValue.length == 0) return true;
    		var d = this.previousValue(j);
    		this.settings.messages[j.name] || (this.settings.messages[j.name] = {});
    		d.originalMessage = this.settings.messages[j.name].remote;
    		this.settings.messages[j.name].remote = d.message;
    		c = c.getParentId();
    		MyFieldNameValue = '{"MyFieldName":"' + MyFieldNameValue + '","elementName":"' + j.name + '"}';
    		if (d.old !== MyFieldNameValue) {
    			d.old = MyFieldNameValue;
    			var n = this;
    			this.startRequest(j); // This is part of jQuery Validation framework which helps in async validation
    			var MyFieldName = encodeURIComponent(a.trim(k));
    			var groupElemContainer = j;
    			
    			// My Custom Validation Async Call comes here
    			WCF.Service.CheckIfValid(MyFieldName, function (response) {
    				j = groupElemContainer;
    				n.settings.messages[j.name].remote = d.originalMessage;
    				var m = response.IsValid === false;
    				if (m) {
    					var f = n.formSubmitted;
    					n.prepareElement(j);
    					n.formSubmitted = f;
    					n.successList.push(j);
    					n.showErrors()
    				} else {
    					f = {};
    					response = d.message = response.Message || n.defaultMessage(j, "MyCustomFieldValidation");
    					f[j.name] = a.isFunction(response) ? message(k) : response;
    					n.showErrors(f)
    				}
    				d.valid = m;
    				n.stopRequest(j, m); // This is part of jQuery Validation framework which helps in async validation
    			});
    			return "pending"
    		} else if (this.pending[j.name]) return "pending";
    		return d.valid
    	}, undefined);
    })(jQuery, window);

     

    Step 2: Use the validation as we use other validation types:

    var myField = jQuery('#txtMyField');
    myField.evolutionValidation('addField',
    myField,
    {
    	required: true,
    	MyCustomFieldValidation: { },
    	messages: {
    		required: "Required",
    		MyFieldNameExists: "The field value is Invalid"
    	}
    },
    myField.closest('.field-item').find('.field-item-validation'), null);

     

    HTML Code:

    <li class="field-item ">
    	<div class="item-label ">
    		<label for="fragment-9986_fieldname">
    		My Custom Field Name:
    	</div>
    	<div class="setting-item-input">
    		<span>
    			<asp:TextBox ID="txtMyField" runat="server" ClientIDMode="Static"></asp:TextBox>
    		</span>
    		<span class="field-item-validation" style="position:absolute;color:red;"></span>
    		<br />
    		<span class="item-description">Instructional text associated with this field
    		</span>
    	</div>
    </li>

    some parts of above javascript are part of Telligent.Evolution.js

    Cheers.

  • In reply to Harsh Baid:

    I agree with and to treat the custom asynchronous validator as invalid until the async process completes, at which point the internal state of the validator is updated and explicitly re-run.

  • In reply to Harsh Baid:

    Its a good solution Harsh, the only one thing I would recommend though is to keep your extensions to the Telligent JavaScript in a separate file if you haven't already, so you don't have to merge your code changes every upgrade.

Related