0

I Need a custom form validation in a textbox

The value should be like this 3-5, so <number>-<number>

Please suggest me some ideas

2
  • did you manage to find a solution to your question?
    – Sander Mangel
    Nov 10 '15 at 14:19
  • no solution found this
    – Magento 2
    Nov 11 '15 at 4:55
1

You can create custom Javascript validation for any form. Inchoo has a post about that and Alan Storm also wrote something about it

After the form is initiated in your html, which would look something like var theForm = new VarienForm('theForm', true); add the following

Validation.add('validate-must-be-number-dash-number','Is not number-number!',function(the_field_value){
    if(the_field_value.match('/[0-9]-[0-9]/ig'))
    {
        return true;
    }
    return false;
});

So, in full; it would look something like this in your form phtml file

<form ... id="theForm">
   [...]
   <input type="text" class="input-text validate-must-be-number-dash-number" value=""/>
   [...]
</form>

<script type="text/javascript">
var theForm = new VarienForm('theForm', true);
Validation.add('validate-must-be-number-dash-number','Is not number-number!',function(the_field_value){
        if(the_field_value.match('/[0-9]-[0-9]/ig'))
        {
            return true;
        }
        return false;
    });
</script>

Now add the class validate-must-be-number-dash-number to your input and you're done

9
  • 3-5 example i need like that
    – Magento 2
    Oct 28 '15 at 10:20
  • I don't think I understand you, what is not ok about above example?
    – Sander Mangel
    Oct 28 '15 at 10:21
  • in this we can use 3-5 only right
    – Magento 2
    Oct 28 '15 at 10:26
  • That is correct, this checks if the value is 3-5, you can alsways tweak it to check for another value. It's basic javascript, nothing fancy there
    – Sander Mangel
    Oct 28 '15 at 10:27
  • that's example i need that format not only 3-5
    – Magento 2
    Oct 28 '15 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.