Validate a number input so it equals sum of two other number inputs

I’m sure this is a daft question and easy to do but I just can’t find the way.

I have three input fields, all are type=number, and I want to validate one of them to make sure it equals the sum of the other two.

Can anyone put me out of my misery?!

Oh the misery, lol.

Can’t you simply just add the two fields and automatically put it in the third field as a read-only field?

Hehe! The first field will be entered first and so I want to make sure it’s correct but still let the person enter the value (to highlight if one of the others was entered wrong).

Add a fourth input, set this to hidden, and set the value of this field to input2 + input3.

You can then use the data-rule-equalto attribute on input 1 to match the sum of inputs 2 + 3 (which will match the figure in the hidden input 4).

Code example:

<!--Checks the user enters 30 in to the first input-->

<input id="text1" name="text1" class="form-control" data-rule-equalto="text4" data-msg-equalto="Please ensure the value matches the sum of the other inputs.">
<input id="text2" name="text2" class="form-control" value="10" type="number">
<input id="text3" name="text3" class="form-control" value="20" type="number">
<input id="text4" name="text4" type="hidden" class="form-control" dmx-bind:value="(text2.value.toNumber() + text3.value.toNumber())">

After reading your recent post it sounds like you need to validate any 1 of the 3 fields rather than just the first? If that’s true the above method will only validate the first input.

1 Like

Perfect. Thanks @max_gb.

Couple of follow-on thoughts…

Can a variable be used instead of a hidden field? Doesn’t really matter, just curious.

Should data-rule-equalto be added to the AC validation options? And I’m guessing there are loads more options like this which could be tapped into?

equalto is actually already available in dmxValidator, it seems though it is only available currently in the UI for password fields.

As far as I’m aware a variable wouldn’t work in this instance as it is querying the name of a field.

Yes, I’ve used it for password fields (the usual ‘enter again’) but it would be good to be there for other field types. I’ll submit a feature request :wink:

Thanks again.

1 Like