3

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.

9

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.

  • 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 – open-ecommerce.org Nov 28 '17 at 11:30
  • yes, that's I have added in 'NOTE'. – chirag Nov 28 '17 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. – open-ecommerce.org Nov 28 '17 at 12:52
1

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>
  • I want to validate only one field from multiple fields in a single form. this will work? – chirag Mar 16 '17 at 8:36
  • Please try & let me know if any query – Ankit Shah Mar 16 '17 at 8:48
  • Still not working. – chirag Mar 16 '17 at 8:58
  • Please post ur whole page code with file path in question – Ankit Shah Mar 16 '17 at 8:59
  • I have created a new button in the registration page and when on clicking i want to validate the first name. – chirag Mar 16 '17 at 9:04

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.