Best JavaScript code snippet using wpt
rails.validations.js
Source:rails.validations.js
1/*!2 * Client Side Validations JS - v0.1.4 (https://github.com/DavyJonesLocker/client_side_validations)3 * Copyright (c) 2020 Geremia Taglialatela, Brian Cardarella4 * Licensed under MIT (https://opensource.org/licenses/mit-license.php)5 */6(function (global, factory) {7 typeof exports === 'object' && typeof module !== 'undefined'8 ? (module.exports = factory(require('jquery')))9 : typeof define === 'function' && define.amd10 ? define(['jquery'], factory)11 : ((global =12 typeof globalThis !== 'undefined' ? globalThis : global || self),13 (global.ClientSideValidations = factory(global.$)));14})(this, function ($) {15 'use strict';16 function _interopDefaultLegacy(e) {17 return e && typeof e === 'object' && 'default' in e ? e : { default: e };18 }19 var $__default = /*#__PURE__*/ _interopDefaultLegacy($);20 function _typeof(obj) {21 '@babel/helpers - typeof';22 if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {23 _typeof = function (obj) {24 return typeof obj;25 };26 } else {27 _typeof = function (obj) {28 return obj &&29 typeof Symbol === 'function' &&30 obj.constructor === Symbol &&31 obj !== Symbol.prototype32 ? 'symbol'33 : typeof obj;34 };35 }36 return _typeof(obj);37 }38 var ClientSideValidations = {39 callbacks: {40 element: {41 after: function after(element, eventData) {},42 before: function before(element, eventData) {},43 fail: function fail(element, message, addError, eventData) {44 return addError();45 },46 pass: function pass(element, removeError, eventData) {47 return removeError();48 },49 },50 form: {51 after: function after(form, eventData) {},52 before: function before(form, eventData) {},53 fail: function fail(form, eventData) {},54 pass: function pass(form, eventData) {},55 },56 },57 eventsToBind: {58 form: function form(_form, $form) {59 return {60 'submit.ClientSideValidations': function submitClientSideValidations(61 eventData62 ) {63 if (64 !$form.isValid(_form.ClientSideValidations.settings.validators)65 ) {66 eventData.preventDefault();67 eventData.stopImmediatePropagation();68 }69 },70 'ajax:beforeSend.ClientSideValidations': function ajaxBeforeSendClientSideValidations(71 eventData72 ) {73 if (eventData.target === this) {74 $form.isValid(_form.ClientSideValidations.settings.validators);75 }76 },77 'form:validate:after.ClientSideValidations': function formValidateAfterClientSideValidations(78 eventData79 ) {80 ClientSideValidations.callbacks.form.after($form, eventData);81 },82 'form:validate:before.ClientSideValidations': function formValidateBeforeClientSideValidations(83 eventData84 ) {85 ClientSideValidations.callbacks.form.before($form, eventData);86 },87 'form:validate:fail.ClientSideValidations': function formValidateFailClientSideValidations(88 eventData89 ) {90 ClientSideValidations.callbacks.form.fail($form, eventData);91 },92 'form:validate:pass.ClientSideValidations': function formValidatePassClientSideValidations(93 eventData94 ) {95 ClientSideValidations.callbacks.form.pass($form, eventData);96 },97 };98 },99 input: function input(form) {100 return {101 'focusout.ClientSideValidations': function focusoutClientSideValidations() {102 $__default['default'](this).isValid(103 form.ClientSideValidations.settings.validators104 );105 },106 'change.ClientSideValidations': function changeClientSideValidations() {107 $__default['default'](this).data('changed', true);108 },109 'element:validate:after.ClientSideValidations': function elementValidateAfterClientSideValidations(110 eventData111 ) {112 ClientSideValidations.callbacks.element.after(113 $__default['default'](this),114 eventData115 );116 },117 'element:validate:before.ClientSideValidations': function elementValidateBeforeClientSideValidations(118 eventData119 ) {120 ClientSideValidations.callbacks.element.before(121 $__default['default'](this),122 eventData123 );124 },125 'element:validate:fail.ClientSideValidations': function elementValidateFailClientSideValidations(126 eventData,127 message128 ) {129 var $element = $__default['default'](this);130 ClientSideValidations.callbacks.element.fail(131 $element,132 message,133 function () {134 return form.ClientSideValidations.addError($element, message);135 },136 eventData137 );138 },139 'element:validate:pass.ClientSideValidations': function elementValidatePassClientSideValidations(140 eventData141 ) {142 var $element = $__default['default'](this);143 ClientSideValidations.callbacks.element.pass(144 $element,145 function () {146 return form.ClientSideValidations.removeError($element);147 },148 eventData149 );150 },151 };152 },153 inputConfirmation: function inputConfirmation(element, form) {154 return {155 'focusout.ClientSideValidations': function focusoutClientSideValidations() {156 element157 .data('changed', true)158 .isValid(form.ClientSideValidations.settings.validators);159 },160 'keyup.ClientSideValidations': function keyupClientSideValidations() {161 element162 .data('changed', true)163 .isValid(form.ClientSideValidations.settings.validators);164 },165 };166 },167 },168 enablers: {169 form: function form(_form2) {170 var $form = $__default['default'](_form2);171 _form2.ClientSideValidations = {172 settings: $form.data('clientSideValidations'),173 addError: function addError(element, message) {174 return ClientSideValidations.formBuilders[175 _form2.ClientSideValidations.settings.html_settings.type176 ].add(177 element,178 _form2.ClientSideValidations.settings.html_settings,179 message180 );181 },182 removeError: function removeError(element) {183 return ClientSideValidations.formBuilders[184 _form2.ClientSideValidations.settings.html_settings.type185 ].remove(186 element,187 _form2.ClientSideValidations.settings.html_settings188 );189 },190 };191 var eventsToBind = ClientSideValidations.eventsToBind.form(192 _form2,193 $form194 );195 for (var eventName in eventsToBind) {196 var eventFunction = eventsToBind[eventName];197 $form.on(eventName, eventFunction);198 }199 $form.find(ClientSideValidations.selectors.inputs).each(function () {200 ClientSideValidations.enablers.input(this);201 });202 },203 input: function input(_input) {204 var $input = $__default['default'](_input);205 var form = _input.form;206 var $form = $__default['default'](form);207 var eventsToBind = ClientSideValidations.eventsToBind.input(form);208 for (var eventName in eventsToBind) {209 var eventFunction = eventsToBind[eventName];210 $input211 .filter(':not(:radio):not([id$=_confirmation])')212 .each(function () {213 return $__default['default'](this).attr('data-validate', true);214 })215 .on(eventName, eventFunction);216 }217 $input218 .filter(':checkbox')219 .on('change.ClientSideValidations', function () {220 $__default['default'](this).isValid(221 form.ClientSideValidations.settings.validators222 );223 });224 $input.filter('[id$=_confirmation]').each(function () {225 var $element = $__default['default'](this);226 var $elementToConfirm = $form.find(227 '#' + this.id.match(/(.+)_confirmation/)[1] + ':input'228 );229 if ($elementToConfirm.length) {230 var _eventsToBind = ClientSideValidations.eventsToBind.inputConfirmation(231 $elementToConfirm,232 form233 );234 for (var _eventName in _eventsToBind) {235 var _eventFunction = _eventsToBind[_eventName];236 $__default['default']('#' + $element.attr('id')).on(237 _eventName,238 _eventFunction239 );240 }241 }242 });243 },244 },245 formBuilders: {246 'ActionView::Helpers::FormBuilder': {247 add: function add(element, settings, message) {248 var form = $__default['default'](element[0].form);249 if (250 element.data('valid') !== false &&251 form.find("label.message[for='" + element.attr('id') + "']")[0] ==252 null253 ) {254 var inputErrorField = $__default['default'](settings.input_tag);255 var labelErrorField = $__default['default'](settings.label_tag);256 var label = form.find(257 "label[for='" + element.attr('id') + "']:not(.message)"258 );259 if (element.attr('autofocus')) {260 element.attr('autofocus', false);261 }262 element.before(inputErrorField);263 inputErrorField.find('span#input_tag').replaceWith(element);264 inputErrorField265 .find('label.message')266 .attr('for', element.attr('id'));267 labelErrorField268 .find('label.message')269 .attr('for', element.attr('id'));270 labelErrorField.insertAfter(label);271 labelErrorField.find('label#label_tag').replaceWith(label);272 }273 form274 .find("label.message[for='" + element.attr('id') + "']")275 .text(message);276 },277 remove: function remove(element, settings) {278 var form = $__default['default'](element[0].form);279 var inputErrorFieldClass = $__default['default'](280 settings.input_tag281 ).attr('class');282 var inputErrorField = element.closest(283 '.' + inputErrorFieldClass.replace(/ /g, '.')284 );285 var label = form.find(286 "label[for='" + element.attr('id') + "']:not(.message)"287 );288 var labelErrorFieldClass = $__default['default'](289 settings.label_tag290 ).attr('class');291 var labelErrorField = label.closest(292 '.' + labelErrorFieldClass.replace(/ /g, '.')293 );294 if (inputErrorField[0]) {295 inputErrorField.find('#' + element.attr('id')).detach();296 inputErrorField.replaceWith(element);297 label.detach();298 labelErrorField.replaceWith(label);299 }300 },301 },302 },303 patterns: {304 numericality: {305 default: new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$'),306 only_integer: new RegExp('^[+-]?\\d+$'),307 },308 },309 selectors: {310 inputs: ':input:not(button):not([type="submit"])[name]:visible:enabled',311 validate_inputs: ':input:enabled:visible[data-validate]',312 forms: 'form[data-client-side-validations]',313 },314 validators: {315 all: function all() {316 return $__default['default'].extend(317 {},318 ClientSideValidations.validators.local,319 ClientSideValidations.validators.remote320 );321 },322 local: {},323 remote: {},324 },325 disable: function disable(target) {326 var $target = $__default['default'](target);327 $target.off('.ClientSideValidations');328 if ($target.is('form')) {329 ClientSideValidations.disable($target.find(':input'));330 } else {331 $target.removeData(['changed', 'valid']);332 $target.filter(':input').each(function () {333 $__default['default'](this).removeAttr('data-validate');334 });335 }336 },337 reset: function reset(form) {338 var $form = $__default['default'](form);339 ClientSideValidations.disable(form);340 for (var key in form.ClientSideValidations.settings.validators) {341 form.ClientSideValidations.removeError(342 $form.find("[name='" + key + "']")343 );344 }345 ClientSideValidations.enablers.form(form);346 },347 start: function start() {348 $__default['default'](function () {349 return $__default['default'](350 ClientSideValidations.selectors.forms351 ).validate();352 });353 },354 };355 var arrayHasValue = function arrayHasValue(value, otherValues) {356 for (var i = 0, l = otherValues.length; i < l; i++) {357 if (value === otherValues[i]) {358 return true;359 }360 }361 return false;362 };363 var valueIsPresent = function valueIsPresent(value) {364 return !/^\s*$/.test(value || '');365 };366 var absenceLocalValidator = function absenceLocalValidator(element, options) {367 if (valueIsPresent(element.val())) {368 return options.message;369 }370 };371 var presenceLocalValidator = function presenceLocalValidator(372 element,373 options374 ) {375 if (!valueIsPresent(element.val())) {376 return options.message;377 }378 };379 var DEFAULT_ACCEPT_OPTION = ['1', true];380 Array.isArray ||381 (Array.isArray = function (a) {382 var object = {};383 return '' + a !== a && object.toString.call(a) === '[object Array]';384 });385 var isTextAccepted = function isTextAccepted(value, acceptOption) {386 if (!acceptOption) {387 acceptOption = DEFAULT_ACCEPT_OPTION;388 }389 if (Array.isArray(acceptOption)) {390 return arrayHasValue(value, acceptOption);391 }392 return value === acceptOption;393 };394 var acceptanceLocalValidator = function acceptanceLocalValidator(395 element,396 options397 ) {398 var valid = true;399 if (element.attr('type') === 'checkbox') {400 valid = element.prop('checked');401 }402 if (element.attr('type') === 'text') {403 valid = isTextAccepted(element.val(), options.accept);404 }405 if (!valid) {406 return options.message;407 }408 };409 var isMatching = function isMatching(value, regExpOptions) {410 return new RegExp(regExpOptions.source, regExpOptions.options).test(value);411 };412 var hasValidFormat = function hasValidFormat(413 value,414 withOptions,415 withoutOptions416 ) {417 return (418 (withOptions && isMatching(value, withOptions)) ||419 (withoutOptions && !isMatching(value, withoutOptions))420 );421 };422 var formatLocalValidator = function formatLocalValidator(element, options) {423 var value = element.val();424 if (options.allow_blank && !valueIsPresent(value)) {425 return;426 }427 if (!hasValidFormat(value, options['with'], options.without)) {428 return options.message;429 }430 };431 var VALIDATIONS = {432 even: function even(a) {433 return parseInt(a, 10) % 2 === 0;434 },435 greater_than: function greater_than(a, b) {436 return parseFloat(a) > parseFloat(b);437 },438 greater_than_or_equal_to: function greater_than_or_equal_to(a, b) {439 return parseFloat(a) >= parseFloat(b);440 },441 equal_to: function equal_to(a, b) {442 return parseFloat(a) === parseFloat(b);443 },444 less_than: function less_than(a, b) {445 return parseFloat(a) < parseFloat(b);446 },447 less_than_or_equal_to: function less_than_or_equal_to(a, b) {448 return parseFloat(a) <= parseFloat(b);449 },450 odd: function odd(a) {451 return parseInt(a, 10) % 2 === 1;452 },453 };454 var getOtherValue = function getOtherValue(validationOption, $form) {455 if (!isNaN(parseFloat(validationOption))) {456 return validationOption;457 }458 var validationElement = $form.find('[name*=' + validationOption + ']');459 if (validationElement.length === 1) {460 var numberFormat = $form[0].ClientSideValidations.settings.number_format;461 var otherFormattedValue = $__default['default']462 .trim(validationElement.val())463 .replace(new RegExp('\\' + numberFormat.separator, 'g'), '.');464 if (!isNaN(parseFloat(otherFormattedValue))) {465 return otherFormattedValue;466 }467 }468 };469 var isValid = function isValid(470 validationFunction,471 validationOption,472 formattedValue,473 $form474 ) {475 if (validationFunction.length === 2) {476 var otherValue = getOtherValue(validationOption, $form);477 return (478 otherValue == null ||479 otherValue === '' ||480 validationFunction(formattedValue, otherValue)481 );482 } else {483 return validationFunction(formattedValue);484 }485 };486 var runFunctionValidations = function runFunctionValidations(487 formattedValue,488 $form,489 options490 ) {491 for (var validation in VALIDATIONS) {492 var validationOption = options[validation];493 var validationFunction = VALIDATIONS[validation]; // Must check for null because this could be 0494 if (validationOption == null) {495 continue;496 }497 if (498 !isValid(validationFunction, validationOption, formattedValue, $form)499 ) {500 return options.messages[validation];501 }502 }503 };504 var runValidations = function runValidations(formattedValue, $form, options) {505 if (506 options.only_integer &&507 !ClientSideValidations.patterns.numericality.only_integer.test(508 formattedValue509 )510 ) {511 return options.messages.only_integer;512 }513 if (514 !ClientSideValidations.patterns.numericality['default'].test(515 formattedValue516 )517 ) {518 return options.messages.numericality;519 }520 return runFunctionValidations(formattedValue, $form, options);521 };522 var numericalityLocalValidator = function numericalityLocalValidator(523 element,524 options525 ) {526 var value = element.val();527 if (options.allow_blank && !valueIsPresent(value)) {528 return;529 }530 var $form = $__default['default'](element[0].form);531 var numberFormat = $form[0].ClientSideValidations.settings.number_format;532 var formattedValue = $__default['default']533 .trim(value)534 .replace(new RegExp('\\' + numberFormat.separator, 'g'), '.');535 return runValidations(formattedValue, $form, options);536 };537 var VALIDATIONS$1 = {538 is: function is(a, b) {539 return a === parseInt(b, 10);540 },541 minimum: function minimum(a, b) {542 return a >= parseInt(b, 10);543 },544 maximum: function maximum(a, b) {545 return a <= parseInt(b, 10);546 },547 };548 var runValidations$1 = function runValidations(valueLength, options) {549 for (var validation in VALIDATIONS$1) {550 var validationOption = options[validation];551 var validationFunction = VALIDATIONS$1[validation];552 if (553 validationOption &&554 !validationFunction(valueLength, validationOption)555 ) {556 return options.messages[validation];557 }558 }559 };560 var lengthLocalValidator = function lengthLocalValidator(element, options) {561 var value = element.val();562 if (options.allow_blank && !valueIsPresent(value)) {563 return;564 }565 return runValidations$1(value.length, options);566 };567 var isInList = function isInList(value, otherValues) {568 var normalizedOtherValues = [];569 for (var otherValueIndex in otherValues) {570 normalizedOtherValues.push(otherValues[otherValueIndex].toString());571 }572 return arrayHasValue(value, normalizedOtherValues);573 };574 var isInRange = function isInRange(value, range) {575 return value >= range[0] && value <= range[1];576 };577 var isIncluded = function isIncluded(value, options, allowBlank) {578 if ((options.allow_blank && !valueIsPresent(value)) === allowBlank) {579 return true;580 }581 return (582 (options['in'] && isInList(value, options['in'])) ||583 (options.range && isInRange(value, options.range))584 );585 };586 var exclusionLocalValidator = function exclusionLocalValidator(587 element,588 options589 ) {590 var value = element.val();591 if (592 isIncluded(value, options, false) ||593 (!options.allow_blank && !valueIsPresent(value))594 ) {595 return options.message;596 }597 };598 var inclusionLocalValidator = function inclusionLocalValidator(599 element,600 options601 ) {602 if (!isIncluded(element.val(), options, true)) {603 return options.message;604 }605 };606 var confirmationLocalValidator = function confirmationLocalValidator(607 element,608 options609 ) {610 var value = element.val();611 var confirmationValue = $__default['default'](612 '#' + element.attr('id') + '_confirmation'613 ).val();614 if (!options.case_sensitive) {615 value = value.toLowerCase();616 confirmationValue = confirmationValue.toLowerCase();617 }618 if (value !== confirmationValue) {619 return options.message;620 }621 };622 var isLocallyUnique = function isLocallyUnique(623 currentElement,624 value,625 otherValue,626 caseSensitive627 ) {628 if (!caseSensitive) {629 value = value.toLowerCase();630 otherValue = otherValue.toLowerCase();631 }632 if (otherValue === value) {633 $__default['default'](currentElement).data('notLocallyUnique', true);634 return false;635 }636 if ($__default['default'](currentElement).data('notLocallyUnique')) {637 $__default['default'](currentElement)638 .removeData('notLocallyUnique')639 .data('changed', true);640 }641 return true;642 };643 var uniquenessLocalValidator = function uniquenessLocalValidator(644 element,645 options646 ) {647 var elementName = element.attr('name');648 var matches = elementName.match(/^(.+_attributes\])\[\d+\](.+)$/);649 if (!matches) {650 return;651 }652 var form = element.closest('form');653 var value = element.val();654 var valid = true;655 form656 .find(':input[name^="' + matches[1] + '"][name$="' + matches[2] + '"]')657 .not(element)658 .each(function () {659 var otherValue = $__default['default'](this).val();660 if (!isLocallyUnique(this, value, otherValue, options.case_sensitive)) {661 valid = false;662 }663 });664 if (!valid) {665 return options.message;666 }667 };668 ClientSideValidations.validators.local = {669 absence: absenceLocalValidator,670 presence: presenceLocalValidator,671 acceptance: acceptanceLocalValidator,672 format: formatLocalValidator,673 numericality: numericalityLocalValidator,674 length: lengthLocalValidator,675 inclusion: inclusionLocalValidator,676 exclusion: exclusionLocalValidator,677 confirmation: confirmationLocalValidator,678 uniqueness: uniquenessLocalValidator,679 };680 $__default['default'].fn.disableClientSideValidations = function () {681 ClientSideValidations.disable(this);682 return this;683 };684 $__default['default'].fn.enableClientSideValidations = function () {685 var _this = this;686 var selectors = {687 forms: 'form',688 inputs: 'input',689 };690 var _loop = function _loop() {691 var enablers = selectors[selector];692 _this.filter(ClientSideValidations.selectors[selector]).each(function () {693 return ClientSideValidations.enablers[enablers](this);694 });695 };696 for (var selector in selectors) {697 _loop();698 }699 return this;700 };701 $__default['default'].fn.resetClientSideValidations = function () {702 this.filter(ClientSideValidations.selectors.forms).each(function () {703 return ClientSideValidations.reset(this);704 });705 return this;706 };707 $__default['default'].fn.validate = function () {708 this.filter(ClientSideValidations.selectors.forms).each(function () {709 return $__default['default'](this).enableClientSideValidations();710 });711 return this;712 };713 $__default['default'].fn.isValid = function (validators) {714 var obj = $__default['default'](this[0]);715 if (obj.is('form')) {716 return validateForm(obj, validators);717 } else {718 return validateElement(obj, validatorsFor(this[0].name, validators));719 }720 };721 var cleanNestedElementName = function cleanNestedElementName(722 elementName,723 nestedMatches,724 validators725 ) {726 for (var validatorName in validators) {727 if (728 validatorName.match(729 '\\[' +730 nestedMatches[1] +731 '\\].*\\[\\]\\[' +732 nestedMatches[2] +733 '\\]$'734 )735 ) {736 elementName = elementName.replace(/\[[\da-z_]+\]\[(\w+)\]$/g, '[][$1]');737 }738 }739 return elementName;740 };741 var cleanElementName = function cleanElementName(elementName, validators) {742 elementName = elementName.replace(743 /\[(\w+_attributes)\]\[[\da-z_]+\](?=\[(?:\w+_attributes)\])/g,744 '[$1][]'745 );746 var nestedMatches = elementName.match(/\[(\w+_attributes)\].*\[(\w+)\]$/);747 if (nestedMatches) {748 elementName = cleanNestedElementName(749 elementName,750 nestedMatches,751 validators752 );753 }754 return elementName;755 };756 var validatorsFor = function validatorsFor(elementName, validators) {757 if (Object.prototype.hasOwnProperty.call(validators, elementName)) {758 return validators[elementName];759 }760 return validators[cleanElementName(elementName, validators)] || {};761 };762 var validateForm = function validateForm(form, validators) {763 var valid = true;764 form.trigger('form:validate:before.ClientSideValidations');765 form766 .find(ClientSideValidations.selectors.validate_inputs)767 .each(function () {768 if (!$__default['default'](this).isValid(validators)) {769 valid = false;770 }771 return true;772 });773 if (valid) {774 form.trigger('form:validate:pass.ClientSideValidations');775 } else {776 form.trigger('form:validate:fail.ClientSideValidations');777 }778 form.trigger('form:validate:after.ClientSideValidations');779 return valid;780 };781 var passElement = function passElement(element) {782 element783 .trigger('element:validate:pass.ClientSideValidations')784 .data('valid', null);785 };786 var failElement = function failElement(element, message) {787 element788 .trigger('element:validate:fail.ClientSideValidations', message)789 .data('valid', false);790 };791 var afterValidate = function afterValidate(element) {792 return (793 element794 .trigger('element:validate:after.ClientSideValidations')795 .data('valid') !== false796 );797 };798 var executeValidator = function executeValidator(799 validatorFunctions,800 validatorFunction,801 validatorOptions,802 element803 ) {804 for (var validatorOption in validatorOptions) {805 if (!validatorOptions[validatorOption]) {806 continue;807 }808 var message = validatorFunction.call(809 validatorFunctions,810 element,811 validatorOptions[validatorOption]812 );813 if (message) {814 failElement(element, message);815 return false;816 }817 }818 return true;819 };820 var executeValidators = function executeValidators(821 validatorFunctions,822 element,823 validators824 ) {825 for (var validator in validators) {826 if (!validatorFunctions[validator]) {827 continue;828 }829 if (830 !executeValidator(831 validatorFunctions,832 validatorFunctions[validator],833 validators[validator],834 element835 )836 ) {837 return false;838 }839 }840 return true;841 };842 var isMarkedForDestroy = function isMarkedForDestroy(element) {843 if (element.attr('name').search(/\[([^\]]*?)\]$/) >= 0) {844 var destroyInputName = element845 .attr('name')846 .replace(/\[([^\]]*?)\]$/, '[_destroy]');847 if (848 $__default['default'](849 "input[name='" + destroyInputName + "']"850 ).val() === '1'851 ) {852 return true;853 }854 }855 return false;856 };857 var executeAllValidators = function executeAllValidators(858 element,859 validators860 ) {861 if (element.data('changed') === false || element.prop('disabled')) {862 return;863 }864 element.data('changed', false);865 if (866 executeValidators(867 ClientSideValidations.validators.all(),868 element,869 validators870 )871 ) {872 passElement(element);873 }874 };875 var validateElement = function validateElement(element, validators) {876 element.trigger('element:validate:before.ClientSideValidations');877 if (isMarkedForDestroy(element)) {878 passElement(element);879 } else {880 executeAllValidators(element, validators);881 }882 return afterValidate(element);883 };884 if (!window.ClientSideValidations) {885 window.ClientSideValidations = ClientSideValidations;886 if (!isAMD() && !isCommonJS()) {887 ClientSideValidations.start();888 }889 }890 function isAMD() {891 return typeof define === 'function' && define.amd; // eslint-disable-line no-undef892 }893 function isCommonJS() {894 return (895 (typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) ===896 'object' && typeof module !== 'undefined'897 ); // eslint-disable-line no-undef898 }899 return ClientSideValidations;...
validations_test.js
Source:validations_test.js
1const sinon = require('sinon');2const assert = require('assert');3const Validations = require('../../src/utils/validations');4const eq = assert.deepStrictEqual;5const ok = (res) => eq(res === undefined ? [] : res, []);6const err = (res, expected) => eq(res, [expected]);7const sandbox = sinon.sandbox.create();8describe('Validations', () => {9 beforeEach(() => {10 sandbox.restore();11 });12 describe('#string', () => {13 it('permits string', () => {14 ok(Validations.string.validate({}, 's', {}, 'abc'));15 });16 it('warns if not a string', () => {17 err(Validations.string.validate({}, 's', {}, []),18 'String param "s" should be a string.');19 });20 it('warns if required and blank', () => {21 ok(Validations.string.validate({}, 's', { required: true }, 'val'));22 err(Validations.string.validate({}, 's', { required: true }, ''),23 'String param "s" should not be blank.');24 });25 });26 describe('#markdown', () => {27 it('permits string', () => {28 ok(Validations.markdown.validate({}, 's', {}, 'abc'));29 });30 it('warns if not a string', () => {31 err(Validations.markdown.validate({}, 's', {}, []),32 'Markdown param "s" should be a string.');33 });34 it('warns if required and blank', () => {35 ok(Validations.markdown.validate({}, 's', { required: true }, 'val'));36 err(Validations.markdown.validate({}, 's', { required: true }, ''),37 'Markdown param "s" should not be blank.');38 });39 });40 describe('#email', () => {41 it('permits email', () => {42 ok(Validations.email.validate({}, 's', {},43 'dispatch@tacosyndicate.family'));44 ok(Validations.email.validate({}, 's', {}, '<test@test.com>'));45 });46 it('permits email and name', () => {47 ok(Validations.email.validate({}, 's', {},48 '"Taco Syndicate Dispatch" <dispatch@tacosyndicate.family>'));49 ok(Validations.email.validate({}, 's', {},50 'Taco Syndicate Dispatch <dispatch@tacosyndicate.family>'));51 ok(Validations.email.validate({}, 's', {},52 '"Gabe\'s Mom" <a-b-c@d_eF.net>'));53 });54 it('warns if not a string', () => {55 err(Validations.email.validate({}, 's', {}, []),56 'Email param "s" should be a string.');57 });58 it('warns if required and blank', () => {59 ok(Validations.email.validate({}, 's', { required: true },60 'val@val.com'));61 err(Validations.email.validate({}, 's', { required: true }, ''),62 'Email param "s" should not be blank.');63 });64 it('warns if not a valid email', () => {65 err(Validations.email.validate({}, 's', {}, 'asdjsadk'),66 'Email param "s" should be a valid email.');67 err(Validations.email.validate({}, 's', {}, 'abc.com'),68 'Email param "s" should be a valid email.');69 err(Validations.email.validate({}, 's', {}, 'john@domain'),70 'Email param "s" should be a valid email.');71 err(Validations.email.validate({}, 's', {}, '"john@domain"'),72 'Email param "s" should be a valid email.');73 err(Validations.email.validate({}, 's', {}, '<john@domain> "test"'),74 'Email param "s" should be a valid email.');75 });76 });77 describe('#color', () => {78 it('permits color', () => {79 ok(Validations.color.validate({}, 's', {}, '#ccaa88'));80 ok(Validations.color.validate({}, 's', {}, '#AABB00'));81 });82 it('warns if not a string', () => {83 err(Validations.color.validate({}, 's', {}, []), 'Color param "s" should be a string.');84 });85 it('warns if blank', () => {86 err(Validations.color.validate({}, 's', {}, ''), 'Color param "s" should not be blank.');87 });88 it('warns if not a valid color', () => {89 err(Validations.color.validate({}, 's', {}, 'aaaaaa'),90 'Color param "s" (aaaaaa) should be a hex color.');91 err(Validations.color.validate({}, 's', {}, '#ff00mz'),92 'Color param "s" (#ff00mz) should be a hex color.');93 err(Validations.color.validate({}, 's', {}, '#000'),94 'Color param "s" (#000) should be a hex color.');95 err(Validations.color.validate({}, 's', {}, '#aacc0'),96 'Color param "s" (#aacc0) should be a hex color.');97 });98 });99 describe('#simpleValue', () => {100 it('permits string, number, or boolean', () => {101 ok(Validations.simpleValue.validate({}, 's', {}, 'abc'));102 ok(Validations.simpleValue.validate({}, 's', {}, 123));103 ok(Validations.simpleValue.validate({}, 's', {}, true));104 ok(Validations.simpleValue.validate({}, 's', {}, false));105 });106 it('warns if not a string, number or boolean', () => {107 err(Validations.simpleValue.validate({}, 's', {}, [1]),108 'Simple param "s" should be a string, number or boolean.');109 err(Validations.simpleValue.validate({}, 's', {}, {a: 2}),110 'Simple param "s" should be a string, number or boolean.');111 });112 it('warns if required and blank', () => {113 ok(Validations.simpleValue.validate({}, 's', { required: true }, 'val'));114 err(Validations.simpleValue.validate({}, 's', { required: true }, ''),115 'Simple param "s" should not be blank.');116 });117 });118 describe('#number', () => {119 it('permits string number', () => {120 ok(Validations.number.validate({}, 's', {}, '1'));121 });122 it('permits number', () => {123 ok(Validations.number.validate({}, 's', {}, 1.5));124 });125 it('warns if not a number', () => {126 err(Validations.number.validate({}, 's', {}, 'abc'),127 'Number param "s" should be a number.');128 });129 });130 describe('#coords', () => {131 it('permits valid coords', () => {132 ok(Validations.coords.validate({}, 's', {}, [42, -18.3]));133 });134 it('warns if not an array of length 2', () => {135 err(Validations.coords.validate({}, 's', {}, 2),136 'Coords param "s" should be an array of two numbers.');137 err(Validations.coords.validate({}, 's', {}, []),138 'Coords param "s" should be an array of two numbers.');139 err(Validations.coords.validate({}, 's', {}, [1, 2, 3]),140 'Coords param "s" should be an array of two numbers.');141 });142 it('warns if coords are out of bounds', () => {143 err(Validations.coords.validate({}, 's', {}, [-1000, 0]),144 'Coords param "s[0]" should be between -180 and 180.');145 err(Validations.coords.validate({}, 's', {}, [32, 230]),146 'Coords param "s[1]" should be between -180 and 180.');147 });148 });149 describe('#timeShorthand', () => {150 it('permits valid time shorthand', () => {151 ok(Validations.timeShorthand.validate({}, 's', {}, '1:00pm'));152 ok(Validations.timeShorthand.validate({}, 's', {}, '12:59am'));153 ok(Validations.timeShorthand.validate({}, 's', {}, '+1d 10:23a'));154 ok(Validations.timeShorthand.validate({}, 's', {}, '+4d 12:00p'));155 });156 it('rejects invalid time shorthand', () => {157 err(Validations.timeShorthand.validate({}, 's', {}, '10:00x'),158 'Time shorthand param "s" ("10:00x") must be valid.');159 err(Validations.timeShorthand.validate({}, 's', {}, '23:00pm'),160 'Time shorthand param "s" ("23:00pm") must be valid.');161 err(Validations.timeShorthand.validate({}, 's', {}, '3:99a'),162 'Time shorthand param "s" ("3:99a") must be valid.');163 err(Validations.timeShorthand.validate({}, 's', {}, '-1d 2:00pm'),164 'Time shorthand param "s" ("-1d 2:00pm") must be valid.');165 err(Validations.timeShorthand.validate({}, 's', {}, 'd 2:00pm'),166 'Time shorthand param "s" ("d 2:00pm") must be valid.');167 });168 });169 describe('#timeOffset', () => {170 it('permits valid offsets', () => {171 ok(Validations.timeOffset.validate({}, 's', {}, '1h'));172 ok(Validations.timeOffset.validate({}, 's', {}, '-600.234m'));173 ok(Validations.timeOffset.validate({}, 's', {}, '0s'));174 ok(Validations.timeOffset.validate({}, 's', {}, '120s'));175 });176 it('rejects invalid time offsets', () => {177 err(Validations.timeOffset.validate({}, 's', {}, 'h'),178 'Time offset param "s" ("h") should be a number suffixed by "h/m/s".');179 err(Validations.timeOffset.validate({}, 's', {}, '10x'),180 'Time offset param "s" ("10x") should be a number suffixed by "h/m/s".');181 err(Validations.timeOffset.validate({}, 's', {}, '1_345s'),182 'Time offset param "s" ("1_345s") should be a number suffixed by "h/m/s".');183 err(Validations.timeOffset.validate({}, 's', {}, '1.2.3m'),184 'Time offset param "s" ("1.2.3m") should be a number suffixed by "h/m/s".');185 err(Validations.timeOffset.validate({}, 's', {}, '1-6d'),186 'Time offset param "s" ("1-6d") should be a number suffixed by "h/m/s".');187 });188 });189 describe('#name', () => {190 const spec = { type: 'name' };191 it('warns if not a string', () => {192 const result = Validations.name.validate({}, 's', spec, 1);193 err(result, 'Name param "s" ("1") should be a string.');194 });195 it('warns if does not start with a letter', () => {196 err(197 Validations.name.validate({}, 's', spec, '1bc'),198 'Name param "s" ("1bc") should start with a letter.');199 err(200 Validations.name.validate({}, 's', spec, '.bc'),201 'Name param "s" (".bc") should start with a letter.');202 });203 it('warns if contains invalid characters', () => {204 err(Validations.name.validate({}, 's', {}, 'a%b'),205 'Name param "s" ("a%b") should be alphanumeric with dashes or underscores.');206 err(Validations.name.validate({}, 's', {}, 'a"-b'),207 'Name param "s" ("a"-b") should be alphanumeric with dashes or underscores.');208 err(Validations.name.validate({}, 's', {}, 'b^$(D'),209 'Name param "s" ("b^$(D") should be alphanumeric with dashes or underscores.');210 });211 });212 describe('#media', () => {213 it('permits URL', () => {214 ok(Validations.media.validate({}, 's', {}, 'https://server/abc.mp3'));215 });216 it('permits lookup', () => {217 ok(Validations.media.validate({}, 's', {}, '{{Role.var_name}}'));218 });219 it('warns if not URL', () => {220 err(Validations.media.validate({}, 's', {}, 'abc.mp3'),221 'Media param "s" must be a URL.');222 });223 it('warns if not a string', () => {224 err(Validations.media.validate({}, 's', {}, 123),225 'Media param "s" should be a string.');226 err(Validations.media.validate({}, 's', {}, false),227 'Media param "s" should be a string.');228 });229 it('warns if required and blank', () => {230 ok(Validations.media.validate({}, 's', { required: true },231 'https://server/path'));232 err(Validations.media.validate({}, 's', { required: true }, ''),233 'Media param "s" should not be blank.');234 });235 });236 describe('#enum', () => {237 it('permits if in enum', () => {238 const spec = { type: 'enum', options: [1, true, 'abc'] };239 ok(Validations.enum.validate({}, 's', spec, 1));240 ok(Validations.enum.validate({}, 's', spec, true));241 ok(Validations.enum.validate({}, 's', spec, 'abc'));242 });243 it('warns if not in enum', () => {244 const spec = { type: 'enum', options: [1, true, 'abc'] };245 err(Validations.enum.validate({}, 's', spec, '1'),246 'Enum param "s" is not one of "1", "true", "abc".');247 err(Validations.enum.validate({}, 's', spec, false),248 'Enum param "s" is not one of "1", "true", "abc".');249 err(Validations.enum.validate({}, 's', spec, 'adc'),250 'Enum param "s" is not one of "1", "true", "abc".');251 });252 });253 describe('#simpleAttribute', () => {254 it('permits valid value names', () => {255 ok(Validations.simpleAttribute.validate({}, 's', {}, 'abc'));256 ok(Validations.simpleAttribute.validate({}, 's', {}, 'A12'));257 ok(Validations.simpleAttribute.validate({}, 's', {}, 'A_BC'));258 });259 it('warns if not a string', () => {260 err(Validations.simpleAttribute.validate({}, 's', {}, 1),261 'Simple attribute param "s" should be a string.');262 });263 it('warns if starts with a number', () => {264 err(Validations.simpleAttribute.validate({}, 's', {}, '0'),265 'Simple attribute param "s" ("0") should start with a letter.');266 });267 it('does not allow quotes', () => {268 err(Validations.simpleAttribute.validate({}, 's', {}, '"abc"'),269 'Simple attribute param "s" (""abc"") should start with a letter.');270 err(Validations.simpleAttribute.validate({}, 's', {}, '\'A\''),271 'Simple attribute param "s" ("\'A\'") should start with a letter.');272 });273 it('warns if contains invalid characters', () => {274 err(Validations.simpleAttribute.validate({}, 's', {}, 'a.b'),275 'Simple attribute param "s" ("a.b") should be alphanumeric with underscores.');276 err(Validations.simpleAttribute.validate({}, 's', {}, 'b^$(D'),277 'Simple attribute param "s" ("b^$(D") should be alphanumeric with underscores.');278 });279 });280 describe('#lookupable', () => {281 it('permits valid value names', () => {282 ok(Validations.lookupable.validate({}, 's', {}, 'abc'));283 ok(Validations.lookupable.validate({}, 's', {}, 'A12'));284 ok(Validations.lookupable.validate({}, 's', {}, 'A_BC'));285 ok(Validations.lookupable.validate({}, 's', {}, 'A-BC'));286 ok(Validations.lookupable.validate({}, 's', {}, 'a.b.c'));287 ok(Validations.lookupable.validate({}, 's', {}, '0'));288 });289 it('permits with quotes', () => {290 ok(Validations.lookupable.validate({}, 's', {}, '"abc"'));291 ok(Validations.lookupable.validate({}, 's', {}, '\'A\''));292 ok(Validations.lookupable.validate({}, 's', {}, '"It\'s a lovely day, Mary Poppins."'));293 });294 it('warns if not a string', () => {295 err(Validations.lookupable.validate({}, 's', {}, 1),296 'Lookupable param "s" ("1") should be a string.');297 });298 it('warns if contains invalid characters', () => {299 err(Validations.lookupable.validate({}, 's', {}, 'a=b'),300 'Lookupable param "s" ("a=b") should be alphanumeric with underscores, dashes and periods.');301 err(Validations.lookupable.validate({}, 's', {}, 'b^$(D'),302 'Lookupable param "s" ("b^$(D") should be alphanumeric with underscores, dashes and periods.');303 });304 });305 describe('#location', () => {306 it('permits full location objects', () => {307 ok(Validations.location.validate({}, 's', {}, { title: 'Test', address: '123 Main St', coords: [1, 2] }));308 ok(Validations.location.validate({}, 's', {}, { title: 'Test', address: '123 Main St', coords: [1.4, 2.2] }));309 });310 it('permits missing address', () => {311 ok(Validations.location.validate({}, 's', {}, { title: 'Test', address: '', coords: [1.4, 2.2] }));312 ok(Validations.location.validate({}, 's', {}, { title: 'Test', coords: [1.4, 2.2] }));313 });314 it('permits missing title', () => {315 ok(Validations.location.validate({}, 's', {}, { title: '', address: '123 Main St', coords: [1.4, 2.2] }));316 ok(Validations.location.validate({}, 's', {}, { address: '123 Main St', coords: [1.4, 2.2] }));317 });318 it('warns if a field is missing', () => {319 err(Validations.location.validate({}, 's', {}, { address: '123 Main St', title: 'Test' }),320 'Location param "s" must be valid: s requires property "coords".');321 });322 it('warns if not an object', () => {323 err(Validations.location.validate({}, 's', {}, '123 Main St'),324 'Location param "s" must be valid: s is not of a type(s) object.');325 });326 });...
inputValidations.js
Source:inputValidations.js
1import { findIndex, mapKeys, forEach, includes, has, isUndefined, reject, isEmpty, size, remove, union } from 'lodash';2/*3* @method : check invalid inputs4*5* @params {object, object} formData, formValidations6*7* @return {array} returns errors[{ target: inputTarget, errors: [{id: 'settings-manager.errorId'}]}]8*9*/10export function checkFormValidity(formData, formValidations, formErrors) {11 const errors = [];12 forEach(formData, (value, key) => { // eslint-disable-line consistent-return13 let valueValidations = formValidations[findIndex(formValidations, ['target', key])];14 let inputErrors = [];15 if (!valueValidations) {16 forEach(formValidations, (data) => {17 if (data.nestedValidations) {18 forEach(data.nestedValidations, (nestedData) => {19 if (nestedData.target === key) valueValidations = nestedData;20 });21 }22 });23 }24 // If section is disabled don't need further checks25 if (includes(key, 'enabled') && !value || !valueValidations) return false;26 forEach(valueValidations.nestedValidations, (nestedValidations) => {27 if (nestedValidations.validations.required && !has(formData, nestedValidations.target)) {28 errors.push({ target: nestedValidations.target, errors: [{ id: 'settings-manager.request.error.validation.required' }] });29 }30 });31 if (!isUndefined(valueValidations)) {32 inputErrors = validate(value, valueValidations.validations);33 }34 if (!isEmpty(inputErrors)) errors.push({ target: key, errors: inputErrors });35 if (formData['security.xframe.value'] && formData['security.xframe.value'] === 'ALLOW-FROM' || formData['security.xframe.value'] === 'ALLOW-FROM.ALLOW-FROM ') {36 errors.push({ target: 'security.xframe.value.nested', errors: [{ id: 'settings-manager.request.error.validation.required' }] });37 }38 });39 return union(formErrors, errors);40}41function validate(value, validations) {42 let errors = [];43 // Handle i18n44 const requiredError = { id: 'settings-manager.request.error.validation.required' };45 mapKeys(validations, (validationValue, validationKey) => {46 switch (validationKey) {47 case 'maxLength':48 if (value.length > validationValue) {49 errors.push({ id: 'settings-manager.request.error.validation.maxLength' });50 }51 break;52 case 'minLength':53 if (value.length < validationValue) {54 errors.push({ id: 'settings-manager.request.error.validation.minLength' });55 }56 break;57 case 'required':58 if (value.length === 0) {59 errors.push({ id: 'settings-manager.request.error.validation.required' });60 }61 break;62 case 'regex':63 if (!new RegExp(validationValue).test(value)) {64 errors.push({ id: 'settings-manager.request.error.validation.regex' });65 }66 break;67 default:68 errors = [];69 }70 });71 if (includes(errors, requiredError)) {72 errors = reject(errors, (error) => error !== requiredError);73 }74 return errors;75}76/*77* @method : get input validations from configs78* @param {object} configs79*80* @return {array} returns formValidations81*/82export function getInputsValidationsFromConfigs(configs) {83 const formValidations = [];84 forEach(configs.sections, (section) => {85 forEach(section.items, (item) => {86 if (!isUndefined(item.target)) {87 const validations = {88 target: item.target,89 validations: item.validations,90 };91 if (has(item, 'items') && item.type !== 'select') {92 validations.nestedValidations = [];93 forEach(item.items, (subItem, key) => {94 if (!isUndefined(subItem.target) && !isUndefined(subItem.validations)) {95 if (has(subItem, 'items')) {96 validations.nestedValidations.push({ target: subItem.target, validations: subItem.validations, nestedValidations: [] });97 forEach(subItem.items, (nestedSubItem) => {98 if (!isUndefined(nestedSubItem.target)) {99 validations.nestedValidations[key].nestedValidations.push({ target: nestedSubItem.target, validations: nestedSubItem.validations });100 }101 });102 } else {103 validations.nestedValidations.push({ target: subItem.target, validations: subItem.validations });104 }105 }106 });107 formValidations.push(validations);108 } else {109 formValidations.push(validations);110 }111 }112 });113 });114 return formValidations;115}116/* eslint-disable no-template-curly-in-string */117/*118*119* Specific to databasePost120*121* @method : check if all required inputs are filled for creating a new database122*123* @params {object} formData124*125* @return {array} returns errors[{ target: inputTarget, errors: [{id: 'settings-manager.errorId'}]}]126*127*/128export function getRequiredInputsDb(data, dbExistsErrors) {129 const formErrors = [130 { target: 'database.connections.${name}.name', errors: [{ id: 'settings-manager.request.error.validation.required' }] },131 { target: 'database.connections.${name}.settings.host', errors: [{ id: 'settings-manager.request.error.validation.required' }] },132 { target: 'database.connections.${name}.settings.port', errors: [{ id: 'settings-manager.request.error.validation.required' }] },133 { target: 'database.connections.${name}.settings.database', errors: [{ id: 'settings-manager.request.error.validation.required' }] },134 ];135 // If size data === 2 user hasn't filled any input,136 if (size(data) === 2) return formErrors;137 forEach(data, (value, target) => {138 if (value !== '') {139 remove(formErrors, (object) => object.target === target);140 }141 });142 return union(dbExistsErrors, formErrors);...
Using AI Code Generation
1var wpt = require('./wpt.js');2var options = {3 videoParams: {4 },5};6var wptInstance = new wpt(options);7wptInstance.runTest(function (err, data) {8 if (err) {9 console.log(err);10 } else {11 console.log(data);12 }13});14wptInstance.getTestStatus(function (err, data) {15 if (err) {16 console.log(err);17 } else {18 console.log(data);19 }20});21wptInstance.getTestResults(function (err, data) {22 if (err) {23 console.log(err);24 } else {25 console.log(data);26 }27});28wptInstance.getTestVideo(function (err, data) {29 if (err) {30 console.log(err);31 } else {32 console.log(data);33 }34});35wptInstance.getTestPageSpeed(function (err, data) {36 if (err) {37 console.log(err);38 } else {39 console.log(data);40 }41});42wptInstance.getTestHar(function (err, data) {43 if (err) {44 console.log(err);45 } else {46 console.log(data);47 }48});49wptInstance.getTestScreenshots(function (err, data) {50 if (err) {51 console.log(err);52 } else {53 console.log(data);54 }55});56wptInstance.getTestRequests(function (err, data) {57 if (err) {58 console.log(err);59 } else {60 console.log(data);61 }62});63wptInstance.getTestBreakdown(function (err, data) {64 if (err) {65 console.log(err);66 } else {67 console.log(data);68 }69});70wptInstance.getTestWaterfall(function (err, data) {71 if (err) {72 console.log(err);
Using AI Code Generation
1const { validate } = require('wptoolkit');2const { validate } = require('wptoolkit');3const { validate } = require('wptoolkit');4const { validate } = require('wptoolkit');5const { validate } = require('wptoolkit');6const { validate } = require('wptoolkit');7const { validate } = require('wptoolkit');8const { validate } = require('wptoolkit');9const { validate } = require('wptoolkit');10validate(11 options: Options = {}12const { validate } = require('wptoolkit');13const isString = (value) => typeof value === 'string';14const isStringAndNotEmpty = (value) =>15 typeof value === 'string' && value.trim() !== '';16const isStringAndNotWhitespace = (value) =>17 typeof value === 'string' && value.trim() !== '';18const isStringAndNotWhitespaceAndNotTooLong = (value) =>19 value.trim() !== '' &&20 value.trim().length <= 10;21const isStringAndNotWhitespaceAndNotTooLongAndNotTooShort = (value) =>22 value.trim() !== '' &&23 value.trim().length <= 10 &&24 value.trim().length >= 3;
Using AI Code Generation
1var wpt = require('./wpt.js');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});8var wpt = require('./wpt.js');9 if (err) {10 console.log(err);11 } else {12 console.log(data);13 }14});15var wpt = require('./wpt.js');16 if (err) {17 console.log(err);18 } else {19 console.log(data);20 }21});22var wpt = require('./wpt.js');23 if (err) {24 console.log(err);25 } else {26 console.log(data);27 }28});29var wpt = require('./wpt.js');30 if (err) {31 console.log(err);32 } else {33 console.log(data);34 }35});36var wpt = require('./wpt.js');37 if (err) {38 console.log(err);39 } else {40 console.log(data);41 }42});43var wpt = require('./wpt.js');44 if (err) {45 console.log(err);46 } else {47 console.log(data);48 }
Using AI Code Generation
1var wpt = require('./wpt.js');2var fs = require('fs');3var config = fs.readFileSync('./config.json');4config = JSON.parse(config);5var wptInstance = new wpt(config.apiKey, config.apiHost);6var test = wptInstance.createTest();7test.setLocation("Dulles_MotoG");8test.setConnection("Cable");9test.setBandwidthDown(1000);10test.setBandwidthUp(1000);11test.setLatency(100);12test.setPacketLoss(1);13test.setVideo(true);14test.setConnectivity("DSL");15test.setBrowser("Chrome");16test.setPrivate(true);17test.setMobile(true);18test.setTimeline(true);19test.setDisableImages(true);20test.setBlockAds(true);21test.setBlockComponents(true);22test.setFirstViewOnly(true);23test.setRuns(1);24test.setFVOnly(true);
Using AI Code Generation
1let wpt = require('./wpt.js');2let path = require('path');3let filePath = path.join(__dirname, 'test.js');4let fileContent = `console.log('hello world');`;5let fileName = 'test.js';6let file = {7};8wpt.validate(file)9 .then((data) => {10 console.log('data', data);11 })12 .catch((err) => {13 console.log('err', err);14 });
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.2f8d7d0c9e0f9c9e8a8d1c6b1b1d7a2a');3}, function(err, data) {4 console.log(data);5});6### wpt.runTest(url, options, callback)7### wpt.getTestResults(testId, callback)8### wpt.getLocations(callback)9### wpt.getTesters(callback)10### wpt.getTestStatus(testId, callback)11### wpt.getLocations(callback)12### wpt.getTesters(callback)13### wpt.getTestStatus(testId, callback)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!