4

In Magento 1.x we can validate individual form field like.

<input class="input-text required-entry" id="name" title="First Name" type="text" name="name" value="" onblur="validate(this)"/>

function validate(id){
   Validation.validate(id);
}

In Magento 2.x How can we validate individual form field?

I want to validate only one field from multiple fields in a single form.

3 Answers 3

13

You can validate specific field using below code of line.

<script>
require([
  'jquery',
  'mage/mage',
], function($){
   $( "#new-button" ).click(function() {        
       $('input[name="field_mobile"]').validation();
       if(!$('input[name="field_mobile"]').validation('isValid')){
           return false;
       }
   });
});
</script>

NOTE: make sure you have added data-mage-init='{"validation":{}} in form tag.

3
  • To make it work you will need to wrap the field with in a form: like it is shown in the other answer by Ankit Shah Commented Nov 28, 2017 at 11:30
  • yes, that's I have added in 'NOTE'. Commented Nov 28, 2017 at 12:26
  • Thanks chirag, but in the question it is not form tag at all so is not completely clear specially when the other answer doesn't have any points. Commented Nov 28, 2017 at 12:52
9

I found this one to work:

$.validator.validateSingleElement('#input-id');

More about how it's implemented and used here: https://mage2.pro/t/topic/5504

0
<form class="form"
      action="<?php Your Action ?>"
      id="form"
      name="form"
      method="post"
      data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>"
      data-mage-init='{"validation":{}}'
      enctype="multipart/form-data" >
<input type="text" name="title" id="title" title="<?php /* @escapeNotVerified */ echo __('Title') ?>" class="input-text data-validate="{required:true}"  value=""  />
</form>
7
  • I want to validate only one field from multiple fields in a single form. this will work? Commented Mar 16, 2017 at 8:36
  • Please try & let me know if any query
    – Jackson
    Commented Mar 16, 2017 at 8:48
  • Still not working. Commented Mar 16, 2017 at 8:58
  • Please post ur whole page code with file path in question
    – Jackson
    Commented Mar 16, 2017 at 8:59
  • I have created a new button in the registration page and when on clicking i want to validate the first name. Commented Mar 16, 2017 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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