1
votes

I'm using knockout validation to validate my view models and put a confirmation or error message next to fields using the custom template. The problem is the confirmation message is being added to fields that are not marked as required. In the template it checks for isModified and isValid but is there a way to check that the field is required so I can only show the confirmation on required fields?

http://jsfiddle.net/uSs3R/

<script type="text/html" id="myCustomTemplate">
    <span data-bind="if: field.isModified() && !field.isValid(), 
                     attr: { title: field.error }"><i class="icon-exclamation-sign"></i></span>
    <span data-bind="if: field.isModified() && field.isValid()"><i class="icon-ok green"></i></span>
</script>
1
To me it works alright? Error symbol on second text field, tick symbol near first text fieldDhana Krishnasamy
@DhanaKrishnasamy I'd like the first field to not have the tick mark since it's not required.NullReference

1 Answers

1
votes

There are multiple solution to this problem:

Don't include your potentially non validateable properties when calling ko.validation.group

So instead of writing:

self.errors = ko.validation.group(self);

just list the properties what you want to validate:

self.errors = ko.validation.group([self.Value2]);

Or you can add an additional check in your custom message template which looks for the field.rules and checks whether it contains any rules:

<script type="text/html" id="myCustomTemplate">
    <span data-bind="if: field.rules().length > 0 && field.isModified() &&      
                      !field.isValid(), attr: { title: field.error }">
           <i class="icon-exclamation-sign"></i>
     </span>
     <span data-bind="if: field.rules().length > 0 && field.isModified() && 
                      field.isValid()">
           <i class="icon-ok green"></i>
     </span>
</script>

Demo JSFiddle.