How can i validate a field

suppose aadhar number which get 12 number as input need to check the input has 12 digit


1 Like

Hi @amal_31845

You can use the below code,

frappe.ui.form.on('Customer', {
    before_save: function(frm) {
        var aadhar_number = frm.doc.custom_aadhar_number; // Replace your fieldname
        
        if (!validateAadharNumber(aadhar_number)) {
        frappe.throw(__('Invalid Aadhar Number. Please enter a valid 12-digit Aadhar Number.'));
        frm.set_value('custom_aadhar_number', '');
        }
    }
});

function validateAadharNumber(aadhar_number) {
    // Aadhar number should be exactly 12 digits
    var aadharRegex = /^\d{12}$/;
    return aadharRegex.test(aadhar_number);
}

Make sure to change your doctype name and field name. I am using the before_save function here so that the field will be validated at the time of saving, and I have also used frappe.throw to make sure that the form will not be saved until it’s validated.

Thanks.

1 Like

You can add a function to the server side method controller called validate, you would see it as def validate(self):
The function would be the logic you require to run and validate before saving the doctype.
Before save is called, method controller Validate is checked, if any methods return a False then the doctype does not save or submit.
https://frappeframework.com/docs/user/en/tutorial/controller-methods

Hi @amal_31845,

Please apply the simple client script for it.

frappe.ui.form.on('Your Doctype', {
    validate: function (frm) {
        var aadharNumber = frm.doc.aadhar_number; // Replace 'aadhar_number' with the actual fieldname in your doctype
        if (aadharNumber && aadharNumber.length !== 12) {
            frappe.msgprint(__('Aadhar card number must be 12 digits.'));
            frappe.validated = false;
        }
    }
});

Please set/check the doctype name and field name according.

I hope this helps.

Thank You!

4 Likes

Thank you @NCP

Actually, this code will allow the user to enter Alphabetical letters too if the field type is data, Aadhar will always contain only numerical digits, so the right code here will be

frappe.ui.form.on('Customer', {
    validate: function (frm) {
        var aadharNumber = frm.doc.custom_aadhar_number; // Replace 'custom_aadhar_number' with the actual fieldname in your doctype
        if (aadharNumber && !/^\d{12}$/.test(aadharNumber)) {
            frappe.msgprint(__('Aadhar card number must be 12 digits.'));
            frappe.validated = false;
        }
    }
});

Thanks.

2 Likes