validate-attr-value.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import standards from '../../standards';
  2. import getRootNode from '../dom/get-root-node';
  3. import { tokenList } from '../../core/utils';
  4. /**
  5. * Validate the value of an ARIA attribute
  6. * @method validateAttrValue
  7. * @memberof axe.commons.aria
  8. * @instance
  9. * @param {HTMLElement} node The element to check
  10. * @param {String} attr The name of the attribute
  11. * @return {Boolean}
  12. */
  13. function validateAttrValue(node, attr) {
  14. let matches;
  15. let list;
  16. const value = node.getAttribute(attr);
  17. const attrInfo = standards.ariaAttrs[attr];
  18. const doc = getRootNode(node);
  19. if (!attrInfo) {
  20. return true;
  21. }
  22. if (attrInfo.allowEmpty && (!value || value.trim() === '')) {
  23. return true;
  24. }
  25. switch (attrInfo.type) {
  26. case 'boolean':
  27. return ['true', 'false'].includes(value.toLowerCase());
  28. case 'nmtoken':
  29. return (
  30. typeof value === 'string' &&
  31. attrInfo.values.includes(value.toLowerCase())
  32. );
  33. case 'nmtokens':
  34. list = tokenList(value);
  35. // Check if any value isn't in the list of values
  36. return list.reduce((result, token) => {
  37. return result && attrInfo.values.includes(token);
  38. // Initial state, fail if the list is empty
  39. }, list.length !== 0);
  40. case 'idref':
  41. return !!(value && doc.getElementById(value));
  42. case 'idrefs':
  43. list = tokenList(value);
  44. return list.some(token => doc.getElementById(token));
  45. case 'string':
  46. // Not allowed empty except with allowEmpty: true
  47. return value.trim() !== '';
  48. case 'decimal':
  49. matches = value.match(/^[-+]?([0-9]*)\.?([0-9]*)$/);
  50. return !!(matches && (matches[1] || matches[2]));
  51. case 'int':
  52. const minValue =
  53. typeof attrInfo.minValue !== 'undefined'
  54. ? attrInfo.minValue
  55. : -Infinity;
  56. return /^[-+]?[0-9]+$/.test(value) && parseInt(value) >= minValue;
  57. }
  58. }
  59. export default validateAttrValue;