A SuiteScript password validation script I've created should catch anytime a password is not exactly 5 characters long, but when I save the record it saves without showing the alert, "password does not match", when the password is not equal to 5. How do I fix this?
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
* @NModuleScope SameAccount
*/
define(['N/currentRecord', 'N/search'],
function(currentRecord, search) {
/**
* Function to be executed after page is initialized.
*
* @param {Object} scriptContext
* @param {Record} scriptContext.currentRecord - Current form record
* @param {string} scriptContext.mode - The mode in which the record is being accessed (create, copy, or edit)
*
* @since 2015.2
*/
function pageInit(scriptContext) {
return true;
}
/**
* Function to be executed when field is changed.
*
* @param {Object} scriptContext
* @param {Record} scriptContext.currentRecord - Current form record
* @param {string} scriptContext.sublistId - Sublist name
* @param {string} scriptContext.fieldId - Field name
* @param {number} scriptContext.lineNum - Line number. Will be undefined if not a sublist or matrix field
* @param {number} scriptContext.columnNum - Line number. Will be undefined if not a matrix field
*
* @since 2015.2
*/
function fieldChanged(scriptContext) {
//alert(JSON.stringify(scriptContext.fieldId));
var objRecord = scriptContext.currentRecord;
if (scriptContext.fieldId === 'custrecord_cc_password'){
var value = objRecord.getValue({
fieldId: 'custrecord_cc_password'
});
if (value.match == 5) {
//alert("OK");
return true;
}
else {
alert("Your password should be 5 digits");
return false;
}
}
match function(it is a function and not a property) is used to match string and not the length of the string.
To validate the length of string, you need to used length property.
So in your case, replacing match with length should do the trick.
if (value.length === 5) {
//alert("OK");
return true;
}
However fieldChanged
event will only be triggered when user updates the password, so to avoid this you should also implement saveRecord
and return false if your validatiion does not pass like below.
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
*/
define([],
function () {
function saveRecord(context) {
var currentRecord = context.currentRecord;
var password = currentRecord.getValue({ fieldId: 'custrecord_cc_password' });
if (password.length < 5) {
// show error
return false;
}
return true;
}
return { saveRecord: saveRecord };
}
);